auth.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Package auth provides authentication and authorization functionality.
  2. package auth
  3. import (
  4. "errors"
  5. "github.com/gin-gonic/gin"
  6. "github.com/runningwater/gohub/app/models/user"
  7. "github.com/runningwater/gohub/pkg/logger"
  8. )
  9. // Attemp login
  10. func Attemp(email, password string) (user.User, error) {
  11. userModel := user.GetByMulti(email)
  12. if userModel.ID == 0 {
  13. return user.User{}, errors.New("账号不存在")
  14. }
  15. if !userModel.ComparePassword(password) {
  16. return user.User{}, errors.New("密码错误")
  17. }
  18. return userModel, nil
  19. }
  20. // LoginByPhone 登陆指定用户
  21. func LoginByPhone(phone string) (user.User, error) {
  22. userModel := user.GetByPhone(phone)
  23. if userModel.ID == 0 {
  24. return user.User{}, errors.New("账号不存在")
  25. }
  26. return userModel, nil
  27. }
  28. // CurrentUser 获取当前用户
  29. func CurrentUser(c *gin.Context) user.User {
  30. userModel, ok := c.MustGet("current_user").(user.User)
  31. if !ok {
  32. logger.LogIf(errors.New("无法获取用户"))
  33. return user.User{}
  34. }
  35. // db is now a *gorm.DB object
  36. return userModel
  37. }
  38. // CurrentUID 获取当前用户 ID
  39. func CurrentUID(c *gin.Context) string {
  40. return c.GetString("current_user_id")
  41. }