auth.go 972 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package users
  2. import (
  3. "log"
  4. "git.ali33.ru/fcg-xvii/go-tools/json"
  5. "git.ali33.ru/fcg-xvii/rest"
  6. "git.ali33.ru/fcg-xvii/rest/example_chat/chat"
  7. )
  8. type Auth struct {
  9. Name string `rest:"required"`
  10. Password string `rest:"required"`
  11. }
  12. func (s *Auth) Validate(req rest.IRequestIn) rest.IRequestOut {
  13. log.Println("VALIDATE")
  14. if req.Auth() == nil {
  15. return req.OutError(rest.ErrorMessage("ErrAuth", "already auth"))
  16. }
  17. return nil
  18. }
  19. func (s *Auth) Execute(req rest.IRequestIn) rest.IRequestOut {
  20. core := req.RCore().(*chat.Chat)
  21. user, check := core.Auth(s.Name, s.Password)
  22. if !check {
  23. return req.OutError(rest.ErrorMessage("ErrAuthData", "user is not found"))
  24. }
  25. authMap := json.Map{
  26. "id": user.ID,
  27. }
  28. token, err := req.GenerateToken(authMap, 0)
  29. if err != nil {
  30. return req.OutError(rest.ErrorMessage("ErrTokenGenerate", err.Error()))
  31. }
  32. req.SetAuth(authMap)
  33. return req.OutSuccess(
  34. json.Map{
  35. "user": user,
  36. "token": token,
  37. },
  38. nil,
  39. )
  40. }