SignIn accepts the user form data and returns a token to authorize a client.
(repo repository.UserRepository)
| 64 | |
| 65 | // SignIn accepts the user form data and returns a token to authorize a client. |
| 66 | func SignIn(repo repository.UserRepository) iris.Handler { |
| 67 | secret := getSecretKey() |
| 68 | signer := jwt.NewSigner(jwt.HS256, []byte(secret), 15*time.Minute) |
| 69 | |
| 70 | return func(ctx iris.Context) { |
| 71 | /* |
| 72 | type LoginForm struct { |
| 73 | Username string `form:"username"` |
| 74 | Password string `form:"password"` |
| 75 | } |
| 76 | and ctx.ReadForm OR use the ctx.FormValue(s) method. |
| 77 | */ |
| 78 | |
| 79 | var ( |
| 80 | username = ctx.FormValue("username") |
| 81 | password = ctx.FormValue("password") |
| 82 | ) |
| 83 | |
| 84 | user, ok := repo.GetByUsernameAndPassword(username, password) |
| 85 | if !ok { |
| 86 | ctx.StopWithText(iris.StatusBadRequest, "wrong username or password") |
| 87 | return |
| 88 | } |
| 89 | |
| 90 | claims := UserClaims{ |
| 91 | UserID: user.ID, |
| 92 | Roles: user.Roles, |
| 93 | } |
| 94 | |
| 95 | // Optionally, generate a JWT ID. |
| 96 | jti, err := util.GenerateUUID() |
| 97 | if err != nil { |
| 98 | ctx.StopWithError(iris.StatusInternalServerError, err) |
| 99 | return |
| 100 | } |
| 101 | |
| 102 | token, err := signer.Sign(claims, jwt.Claims{ |
| 103 | ID: jti, |
| 104 | Issuer: util.AppName, |
| 105 | }) |
| 106 | if err != nil { |
| 107 | ctx.StopWithError(iris.StatusInternalServerError, err) |
| 108 | return |
| 109 | } |
| 110 | |
| 111 | ctx.Write(token) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | // SignOut invalidates a user from server-side using the jwt Blocklist. |
| 116 | func SignOut(ctx iris.Context) { |
no test coverage detected
searching dependent graphs…