// update password func UserUpdatePassword(v interface{}) *Result { form, ok := v.(*PasswordForm) if !ok { return ErrorResult(paramTypeError(new(PasswordForm))) } // check confirm password if form.New != form.Confirm { return ErrorResult(ERR_PASSWORD_CONFIRM) } // get old user u, err := model.GetUserBy("id", form.Id) if err != nil { return ErrorResult(err) } // user not found if u == nil || u.Id != form.Id { return ErrorResult(ERR_USERNAME_NOT_FOUND) } // check password if !u.CheckPassword(form.Old) { return ErrorResult(ERR_PASSWORD_INCORRECT) } u.Password = form.New // save password if err = model.UpdateUserPassword(u); err != nil { return ErrorResult(err) } return OkResult(nil) }
// user auth action func UserAuth(v interface{}) *Result { tokenString, ok := v.(string) if !ok { return ErrorResult(paramTypeError("")) } // get token token, err := model.GetAndValidateToken(tokenString) if err != nil { if err.Error() == "expired" { return ErrorResult(ERR_TOKEN_EXPIRED) } return ErrorResult(err) } // get user user, err := model.GetUserBy("id", token.UserId) if err != nil { return ErrorResult(err) } return OkResult(map[string]interface{}{ "user": user, "token": token, }) }
// user login action func UserLogin(v interface{}) *Result { form, ok := v.(*LoginForm) if !ok { return ErrorResult(paramTypeError(new(LoginForm))) } // get user u, err := model.GetUserBy("name", form.Username) if err != nil { return ErrorResult(err) } if u.Id == 0 { // user not found return ErrorResult(ERR_USERNAME_NOT_FOUND) } // check password if !u.CheckPassword(form.Password) { return ErrorResult(ERR_PASSWORD_INCORRECT) } // create token t := &model.Token{ UserId: u.Id, Value: fmt.Sprintf("%d", time.Now().UnixNano()), ExpireTime: time.Now().Add(24 * time.Hour).Unix(), } t.EncodeValue() if err = model.SaveToken(t); err != nil { return ErrorResult(err) } // return user and token data return OkResult(map[string]interface{}{ "user": u, "token": t, }) }