func (r *resourceAuth) Login(email string, password string) (*models.User, error) { user := newResourceUser.GetByEmail(email) if user == nil { return nil, apiErrors.ThrowError(apiErrors.AuthEmailInvalid) } if !newResourceUser.IsMatchPassword(user.Password, password) { return nil, apiErrors.ThrowError(apiErrors.AuthPasswordInValid) } return user, nil }
func (r *resourceUser) Edit(id string, u *models.User) error { if !bson.IsObjectIdHex(id) { return apiErrors.ThrowError(apiErrors.IdInvalid) } u.Id = "" if err := collection(userColName).UpdateId(bson.ObjectIdHex(id), u); err != nil { if err == mgo.ErrNotFound { return apiErrors.ThrowError(apiErrors.UserNotFound) } panic(err) } return nil }
func (r *resourceUser) GetById(id string) (*models.User, error) { if !bson.IsObjectIdHex(id) { return nil, apiErrors.ThrowError(apiErrors.IdInvalid) } var user models.User if err := collection(userColName).FindId(bson.ObjectIdHex(id)).One(&user); err != nil { if err == mgo.ErrNotFound { return nil, apiErrors.ThrowError(apiErrors.UserNotFound) } panic(err) } return &user, nil }
func (e *errorController) GetById(c *gin.Context) { var errorId string if errorId = c.Param("errorId"); errorId == "" { if errorId = c.Request.URL.Query().Get("errorId"); errorId == "" { c.Error(apiErrors.ThrowError(apiErrors.ApiErrorIdRequied)) return } } apiError := apiErrors.FindErrorById(errorId) if apiError == nil { c.Error(apiErrors.ThrowError(apiErrors.ApiErrorNotFound)) return } c.JSON(200, apiError) }
func (a *authMiddleware) RequireLogin() gin.HandlerFunc { return func(c *gin.Context) { token, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) { b := ([]byte(config.GetSecret())) return b, nil }) if err != nil || token == nil || (token != nil && !token.Valid) { c.Error(apiErrors.ThrowError(apiErrors.AccessDenied)) c.Abort() return } var currentUser *models.User var findUserErr error if userId, ok := token.Claims["userId"].(string); ok { if currentUser, findUserErr = userResource.GetById(userId); findUserErr != nil { c.Error(findUserErr) c.Abort() return } } else { panic("Must load userId in token") } c.Set("currentUser", currentUser) c.Next() } }
func (r *resourceUser) Create(u *models.User) error { if u.Password == "" { return apiErrors.ThrowError(apiErrors.UserPasswordRequired) } u.Password = r.HashPassword(u.Password) u.Id = bson.NewObjectId() u.Role = models.NormalUser if err := collection(userColName).Insert(u); err != nil { if mgo.IsDup(err) { return apiErrors.ThrowError(apiErrors.UserExist) } panic(err) } return nil }
/** TODO: - Get email and password from post request - Find user **/ func (a *authController) Login(c *gin.Context) { var userLogin models.UserLogin if err := c.Bind(&userLogin); err != nil { panic(err) } user, err := authResource.Login(userLogin.Email, userLogin.Password) if err != nil { c.Error(err) return } token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256")) // Set some claims token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix() // Sign and get the complete encoded token as a string apiKey, err := token.SignedString([]byte(config.GetSecret())) if err != nil { c.Error(apiErrors.ThrowError(apiErrors.ServerError)) return } // Remove password user.Password = "" c.JSON(200, gin.H{ "user": user, "api-key": apiKey, }) }
func (r *resourceUser) GetByEmail(email string) (*models.User, error) { var user models.User if err := collection(userColName).Find(bson.M{"email": email}).One(&user); err != nil { if err == mgo.ErrNotFound { return nil, apiErrors.ThrowError(apiErrors.UserNotFound) } panic(err) } return &user, nil }
func (a *authMiddleware) UserRequirePermission(role int) gin.HandlerFunc { return func(c *gin.Context) { currentUser := utils.MustGetCurrentUser(c) if currentUser.Role < role { c.Error(apiErrors.ThrowError(apiErrors.AccessDenied)) c.Abort() return } c.Next() } }
/** TODO: - Check user is login - If not return not login error - If logined set "user" in context **/ func (a *authMiddleware) RequireLogin() gin.HandlerFunc { return func(c *gin.Context) { user, err := jwt_lib.ParseFromRequest(c.Request, func(token *jwt_lib.Token) (interface{}, error) { b := ([]byte(config.GetSecret())) return b, nil }) if err != nil { c.Error(apiErrors.ThrowError(apiErrors.UserNotLogined)) return } c.Set("user", user) } }
func (a *authMiddleware) UserHasAuthorization() gin.HandlerFunc { return func(c *gin.Context) { currentUser := utils.MustGetCurrentUser(c) userData := utils.MustGetUserData(c) if currentUser.Role == models.NormalUser { if currentUser.Id != userData.Id { c.Error(apiErrors.ThrowError(apiErrors.AccessDenied)) c.Abort() return } } else { if currentUser.Role <= userData.Role { c.Error(apiErrors.ThrowError(apiErrors.AccessDenied)) c.Abort() return } } c.Next() } }
func Recovery() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { serverError := apiErrors.ThrowError(apiErrors.ServerError) c.JSON(serverError.Status, gin.H{ "message": serverError.Message, "id": serverError.Id, }) return } }() c.Next() } }
func (r *resourceUser) ParseError(err error) []error { var errors []error if errs, ok := err.(*validator.StructErrors); ok { for _, v := range errs.Errors { switch v.Field { case "Email": switch v.Tag { case "required": errors = append(errors, apiErrors.ThrowError(apiErrors.UserEmailRequied)) case "email": errors = append(errors, apiErrors.ThrowError(apiErrors.UserEmailInvalid)) case "max": errors = append(errors, apiErrors.ThrowError(apiErrors.UserEmailMax)) case "min": errors = append(errors, apiErrors.ThrowError(apiErrors.UserEmailMin)) } case "Password": switch v.Tag { case "required": errors = append(errors, apiErrors.ThrowError(apiErrors.UserPasswordRequired)) } case "Role": switch v.Tag { case "max": errors = append(errors, apiErrors.ThrowError(apiErrors.UserRoleMax)) case "min": errors = append(errors, apiErrors.ThrowError(apiErrors.UserRoleMin)) } } } } else { panic("Can not parse error") } return errors }