vikunja-api/routes/api/v1/login.go

70 lines
1.6 KiB
Go
Raw Normal View History

2018-06-10 11:34:59 +02:00
package v1
2018-06-10 11:11:41 +02:00
import (
2018-07-25 17:30:29 +02:00
"code.vikunja.io/api/models"
2018-06-10 11:11:41 +02:00
"crypto/md5"
"encoding/hex"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/spf13/viper"
2018-06-10 11:11:41 +02:00
"net/http"
"time"
)
// Login is the login handler
func Login(c echo.Context) error {
2018-06-13 13:45:22 +02:00
// swagger:operation POST /login user login
// ---
// summary: Logs a user in. Returns a JWT-Token to authenticate requests
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/UserLogin"
// responses:
// "200":
// "$ref": "#/responses/Token"
// "400":
// "$ref": "#/responses/Message"
// "403":
// "$ref": "#/responses/Message"
2018-07-11 00:28:53 +02:00
u := models.UserLogin{}
if err := c.Bind(&u); err != nil {
2018-06-10 11:11:41 +02:00
return c.JSON(http.StatusBadRequest, models.Message{"Please provide a username and password."})
}
// Check user
2018-07-11 00:28:53 +02:00
user, err := models.CheckUserCredentials(&u)
2018-06-10 11:11:41 +02:00
if err != nil {
return c.JSON(http.StatusUnauthorized, models.Message{"Wrong username or password."})
}
// Create token
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := token.Claims.(jwt.MapClaims)
claims["username"] = user.Username
claims["email"] = user.Email
claims["id"] = user.ID
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
avatar := md5.Sum([]byte(user.Email))
claims["avatar"] = hex.EncodeToString(avatar[:])
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(viper.GetString("service.JWTSecret")))
2018-06-10 11:11:41 +02:00
if err != nil {
return err
}
return c.JSON(http.StatusOK, map[string]string{
"token": t,
})
}