Gin框架与《Web Development with Go》实践(六)

Users资源的处理函数

src/taskmanager2/routers2/user.go

package routers2

import (
    "gopkg.in/gin-gonic/gin.v1"
    "taskmanager2/controllers2"
)

func SetUserRoutes(router *gin.Engine) *gin.Engine {

    userR := router.Group("/tm2/users")
    {
        userR.POST("/register", controllers2.Register)
        userR.POST("/login", controllers2.Login)
    }
    return router
}

JSON资源模型

src/taskmanager2/controllers2/resources.go

package controllers2

import (
    "taskmanager2/models2"
)

type (
    UserResource struct {
        Data models2.User `json:"data"`
    }
    LoginResource struct {
        Data LoginModel `json:"data"`
    }
    AuthUserResource struct {
        Data AuthUserModel `json:"data"`
    }
    TaskResource struct {
        Data models2.Task `json:"data"`
    }
    TasksResource struct {
        Data []models2.Task `json:"data"`
    }
    NoteResource struct {
        Data NoteModel `json:"data"`
    }
    LoginModel struct {
        Email    string `json:"email"`
        Password string `json:"password"`
    }
    AuthUserModel struct {
        User  models2.User `json:"user"`
        Token string      `json:"token"`
    }
    NoteModel struct {
        TaskId      string `json:"taskid"`
        Description string `json:"description"`
    }
)

Users资源的处理函数

src/taskmanager2/controllers2/userCtrler.go
对应路径“/tm2/users/register”

package controllers2

import (
    "net/http"
    "gopkg.in/gin-gonic/gin.v1"
    "taskmanager2/common2"
    "taskmanager2/data2"
    "taskmanager2/models2"
)

// Handler for HTTP Post - /tm2/users/register
func Register(c *gin.Context) {
    var dataResource UserResource

    err := c.BindJSON(&dataResource)
    if err != nil {
        common2.DisplayAppError(
            c,
            err,
            "Invalid User data",
            500,
        )
        return
    }

    user := &dataResource.Data
    context := NewContext()
    defer context.Close()
    col := context.DbCollection("users")
    repo := &data2.UserRepository{C: col}
    repo.CreateUser(user)
    // Clean-up the hashpassword to eliminate it from response JSON
    user.HashPassword = nil

    c.JSON(http.StatusCreated, dataResource)
}
...

src/taskmanager2/controllers2/userCtrler.go
对应路径“/tm2/users/login”

...
// Handler for HTTP Post - /tm2/users/login
func Login(c *gin.Context) {
    var dataResource LoginResource
    var token string
    // Decode the incoming Login json
    err := c.BindJSON(&dataResource)
    if err != nil {
        common2.DisplayAppError(
            c,
            err,
            "Invalid Login data",
            500,
        )
        return
    }
    loginModel := dataResource.Data
    loginUser := models2.User{
        Email:    loginModel.Email,
        Password: loginModel.Password,
    }
    context := NewContext()
    defer context.Close()
    col := context.DbCollection("users")
    repo := &data2.UserRepository{C: col}
    // Authenticate the login user
    user, err := repo.Login(loginUser)
    if err != nil {
        common2.DisplayAppError(
            c,
            err,
            "Invalid login credentials",
            401,
        )
        return
    }
    // Generate JWT token
    token, err = common2.GenerateJWT(user.Email, "member")
    if err != nil {
        common2.DisplayAppError(
            c,
            err,
            "Eror while generating the access token",
            500,
        )
        return
    }

    // Clean-up the hashpassword to eliminate it from response JSON
    user.HashPassword = nil
    authUser := AuthUserModel{
        User:  user,
        Token: token,
    }

    c.JSON(http.StatusOK, AuthUserResource{Data: authUser})
}

注册新用户

使用mongodb:


Gin框架与《Web Development with Go》实践(六)_第1张图片

使用图形工具:


Gin框架与《Web Development with Go》实践(六)_第2张图片

src/taskmanager2/data2/userRepository.go

package data2

import (
    "golang.org/x/crypto/bcrypt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"

    "taskmanager2/models2"
)

type UserRepository struct {
    C *mgo.Collection
}

func (r *UserRepository) CreateUser(user *models2.User) error {
    obj_id := bson.NewObjectId()
    user.Id = obj_id
    hpass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
    if err != nil {
        panic(err)
    }
    user.HashPassword = hpass
    //clear the incoming text password
    user.Password = ""
    err = r.C.Insert(&user)
    return err
}

func (r *UserRepository) Login(user models2.User) (u models2.User, err error) {

    err = r.C.Find(bson.M{"email": user.Email}).One(&u)
    if err != nil {
        return
    }
    // Validate password
    err = bcrypt.CompareHashAndPassword(u.HashPassword, []byte(user.Password))
    if err != nil {
        u = models2.User{}
    }
    return
}

使用postman进行注册:


Gin框架与《Web Development with Go》实践(六)_第3张图片
user-register.png

其响应为:

Gin框架与《Web Development with Go》实践(六)_第4张图片

查看数据库:

Gin框架与《Web Development with Go》实践(六)_第5张图片

登录进系统

在postman中进行新用户的登录:

Gin框架与《Web Development with Go》实践(六)_第6张图片

登录后的相应如下,其中有jwt值的返回:

Gin框架与《Web Development with Go》实践(六)_第7张图片

你可能感兴趣的:(Gin框架与《Web Development with Go》实践(六))