1
0

Authentication with OpenID Connect providers (#713)

Add config docs

Lint

Move provider-related stuff to separate file

Refactor getting auth providers

Fix tests

Fix user tests

Fix openid tests

Add swagger docs

Fix lint

Fix lint issues

Fix checking if the user already exists

Make sure to create a new namespace for new users

Docs

Add tests for openid

Remove unnessecary err check

Consistently return nil users if creating a new user failed

Move sending confirmation email to separate function

Better variable names

Move checks to separate functions

Refactor creating user into seperate file

Fix creating new local users

Test creating new users from different issuers

Generate a random username right away if no preferred username has been given

Add todo

Cache openid providers

Add getting int clientids

Fix migration

Move creating tokens to auth package

Add getting or creating a third party user

Add parsing claims

Add retreiving auth tokens

Add token callback from openid package

Add check for provider key

Add routes

Start adding openid auth handler

Add config for openid auth

Co-authored-by: kolaente <k@knt.li>
Reviewed-on: https://kolaente.dev/vikunja/api/pulls/713
Co-Authored-By: konrad <konrad@kola-entertainments.de>
Co-Committed-By: konrad <konrad@kola-entertainments.de>
This commit is contained in:
konrad
2020-11-21 16:38:58 +00:00
parent f67fe2ce25
commit 2b5c9ae7a8
37 changed files with 1265 additions and 178 deletions

View File

@ -1,84 +0,0 @@
// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-2020 Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package v1
import (
"net/http"
"time"
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/user"
"code.vikunja.io/web"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
)
// These are all valid auth types
const (
AuthTypeUnknown int = iota
AuthTypeUser
AuthTypeLinkShare
)
// NewUserJWTAuthtoken generates and signes a new jwt token for a user. This is a global function to be able to call it from integration tests.
func NewUserJWTAuthtoken(user *user.User) (token string, err error) {
t := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := t.Claims.(jwt.MapClaims)
claims["type"] = AuthTypeUser
claims["id"] = user.ID
claims["username"] = user.Username
claims["email"] = user.Email
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Generate encoded token and send it as response.
return t.SignedString([]byte(config.ServiceJWTSecret.GetString()))
}
// NewLinkShareJWTAuthtoken creates a new jwt token from a link share
func NewLinkShareJWTAuthtoken(share *models.LinkSharing) (token string, err error) {
t := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := t.Claims.(jwt.MapClaims)
claims["type"] = AuthTypeLinkShare
claims["id"] = share.ID
claims["hash"] = share.Hash
claims["list_id"] = share.ListID
claims["right"] = share.Right
claims["sharedByID"] = share.SharedByID
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Generate encoded token and send it as response.
return t.SignedString([]byte(config.ServiceJWTSecret.GetString()))
}
// GetAuthFromClaims returns a web.Auth object from jwt claims
func GetAuthFromClaims(c echo.Context) (a web.Auth, err error) {
jwtinf := c.Get("user").(*jwt.Token)
claims := jwtinf.Claims.(jwt.MapClaims)
typ := int(claims["type"].(float64))
if typ == AuthTypeLinkShare && config.ServiceEnableLinkSharing.GetBool() {
return models.GetLinkShareFromClaims(claims)
}
if typ == AuthTypeUser {
return user.GetUserFromClaims(claims)
}
return nil, echo.NewHTTPError(http.StatusBadRequest, models.Message{Message: "Invalid JWT token."})
}

View File

@ -20,6 +20,7 @@ import (
"net/http"
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/modules/auth/openid"
"code.vikunja.io/api/pkg/modules/migration/todoist"
"code.vikunja.io/api/pkg/modules/migration/wunderlist"
"code.vikunja.io/api/pkg/version"
@ -39,6 +40,22 @@ type vikunjaInfos struct {
TotpEnabled bool `json:"totp_enabled"`
Legal legalInfo `json:"legal"`
CaldavEnabled bool `json:"caldav_enabled"`
AuthInfo authInfo `json:"auth"`
}
type authInfo struct {
Local localAuthInfo `json:"local"`
OpenIDConnect openIDAuthInfo `json:"openid_connect"`
}
type localAuthInfo struct {
Enabled bool `json:"enabled"`
}
type openIDAuthInfo struct {
Enabled bool `json:"enabled"`
RedirectURL string `json:"redirect_url"`
Providers []*openid.Provider `json:"providers"`
}
type legalInfo struct {
@ -68,8 +85,24 @@ func Info(c echo.Context) error {
ImprintURL: config.LegalImprintURL.GetString(),
PrivacyPolicyURL: config.LegalPrivacyURL.GetString(),
},
AuthInfo: authInfo{
Local: localAuthInfo{
Enabled: config.AuthLocalEnabled.GetBool(),
},
OpenIDConnect: openIDAuthInfo{
Enabled: config.AuthOpenIDEnabled.GetBool(),
RedirectURL: config.AuthOpenIDRedirectURL.GetString(),
},
},
}
providers, err := openid.GetAllProviders()
if err != nil {
return err
}
info.AuthInfo.OpenIDConnect.Providers = providers
// Migrators
if config.MigrationWunderlistEnable.GetBool() {
m := &wunderlist.Migration{}

View File

@ -20,13 +20,14 @@ import (
"net/http"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/web/handler"
"github.com/labstack/echo/v4"
)
// LinkShareToken represents a link share auth token with extra infos about the actual link share
type LinkShareToken struct {
Token
auth.Token
*models.LinkSharing
ListID int64 `json:"list_id"`
}
@ -38,7 +39,7 @@ type LinkShareToken struct {
// @Accept json
// @Produce json
// @Param share path string true "The share hash"
// @Success 200 {object} v1.Token "The valid jwt auth token."
// @Success 200 {object} auth.Token "The valid jwt auth token."
// @Failure 400 {object} web.HTTPError "Invalid link share object provided."
// @Failure 500 {object} models.Message "Internal error"
// @Router /shares/{share}/auth [post]
@ -49,13 +50,13 @@ func AuthenticateLinkShare(c echo.Context) error {
return handler.HandleHTTPError(err, c)
}
t, err := NewLinkShareJWTAuthtoken(share)
t, err := auth.NewLinkShareJWTAuthtoken(share)
if err != nil {
return handler.HandleHTTPError(err, c)
}
return c.JSON(http.StatusOK, LinkShareToken{
Token: Token{Token: t},
Token: auth.Token{Token: t},
LinkSharing: share,
ListID: share.ListID,
})

View File

@ -20,17 +20,13 @@ import (
"net/http"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/modules/auth"
user2 "code.vikunja.io/api/pkg/user"
"code.vikunja.io/web/handler"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
)
// Token represents an authentification token
type Token struct {
Token string `json:"token"`
}
// Login is the login handler
// @Summary Login
// @Description Logs a user in. Returns a JWT-Token to authenticate further requests.
@ -38,7 +34,7 @@ type Token struct {
// @Accept json
// @Produce json
// @Param credentials body user.Login true "The login credentials"
// @Success 200 {object} v1.Token
// @Success 200 {object} auth.Token
// @Failure 400 {object} models.Message "Invalid user password model."
// @Failure 412 {object} models.Message "Invalid totp passcode."
// @Failure 403 {object} models.Message "Invalid username or password."
@ -71,12 +67,7 @@ func Login(c echo.Context) error {
}
// Create token
t, err := NewUserJWTAuthtoken(user)
if err != nil {
return err
}
return c.JSON(http.StatusOK, Token{Token: t})
return auth.NewUserAuthTokenResponse(user, c)
}
// RenewToken gives a new token to every user with a valid token
@ -86,7 +77,7 @@ func Login(c echo.Context) error {
// @tags user
// @Accept json
// @Produce json
// @Success 200 {object} v1.Token
// @Success 200 {object} auth.Token
// @Failure 400 {object} models.Message "Only user token are available for renew."
// @Router /user/token [post]
func RenewToken(c echo.Context) (err error) {
@ -94,18 +85,18 @@ func RenewToken(c echo.Context) (err error) {
jwtinf := c.Get("user").(*jwt.Token)
claims := jwtinf.Claims.(jwt.MapClaims)
typ := int(claims["type"].(float64))
if typ == AuthTypeLinkShare {
if typ == auth.AuthTypeLinkShare {
share := &models.LinkSharing{}
share.ID = int64(claims["id"].(float64))
err := share.ReadOne()
if err != nil {
return handler.HandleHTTPError(err, c)
}
t, err := NewLinkShareJWTAuthtoken(share)
t, err := auth.NewLinkShareJWTAuthtoken(share)
if err != nil {
return handler.HandleHTTPError(err, c)
}
return c.JSON(http.StatusOK, Token{Token: t})
return c.JSON(http.StatusOK, auth.Token{Token: t})
}
user, err := user2.GetUserFromClaims(claims)
@ -114,10 +105,5 @@ func RenewToken(c echo.Context) (err error) {
}
// Create token
t, err := NewUserJWTAuthtoken(user)
if err != nil {
return err
}
return c.JSON(http.StatusOK, Token{Token: t})
return auth.NewUserAuthTokenResponse(user, c)
}

View File

@ -20,6 +20,7 @@ import (
"net/http"
"code.vikunja.io/api/pkg/models"
auth2 "code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/web/handler"
"github.com/labstack/echo/v4"
)
@ -46,7 +47,7 @@ func UploadTaskAttachment(c echo.Context) error {
}
// Rights check
auth, err := GetAuthFromClaims(c)
auth, err := auth2.GetAuthFromClaims(c)
if err != nil {
return handler.HandleHTTPError(err, c)
}
@ -116,7 +117,7 @@ func GetTaskAttachment(c echo.Context) error {
}
// Rights check
auth, err := GetAuthFromClaims(c)
auth, err := auth2.GetAuthFromClaims(c)
if err != nil {
return handler.HandleHTTPError(err, c)
}

View File

@ -21,6 +21,7 @@ import (
"strconv"
"code.vikunja.io/api/pkg/models"
auth2 "code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/api/pkg/user"
"code.vikunja.io/web/handler"
"github.com/labstack/echo/v4"
@ -74,7 +75,7 @@ func ListUsersForList(c echo.Context) error {
}
list := models.List{ID: listID}
auth, err := GetAuthFromClaims(c)
auth, err := auth2.GetAuthFromClaims(c)
if err != nil {
return handler.HandleHTTPError(err, c)
}

View File

@ -57,8 +57,7 @@ func RegisterUser(c echo.Context) error {
}
// Add its namespace
newN := &models.Namespace{Title: newUser.Username, Description: newUser.Username + "'s namespace.", Owner: newUser}
err = newN.Create(newUser)
err = models.CreateNewNamespaceForUser(newUser)
if err != nil {
return handler.HandleHTTPError(err, c)
}

View File

@ -22,7 +22,7 @@ import (
"code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/metrics"
"code.vikunja.io/api/pkg/models"
v1 "code.vikunja.io/api/pkg/routes/api/v1"
auth2 "code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/api/pkg/user"
"github.com/labstack/echo/v4"
"github.com/prometheus/client_golang/prometheus/promhttp"
@ -95,7 +95,7 @@ func setupMetricsMiddleware(a *echo.Group) {
// updateActiveUsersFromContext updates the currently active users in redis
func updateActiveUsersFromContext(c echo.Context) (err error) {
auth, err := v1.GetAuthFromClaims(c)
auth, err := auth2.GetAuthFromClaims(c)
if err != nil {
return
}

View File

@ -24,8 +24,8 @@ import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log"
auth2 "code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/api/pkg/red"
apiv1 "code.vikunja.io/api/pkg/routes/api/v1"
"github.com/labstack/echo/v4"
"github.com/ulule/limiter/v3"
"github.com/ulule/limiter/v3/drivers/store/memory"
@ -41,7 +41,7 @@ func RateLimit(rateLimiter *limiter.Limiter, rateLimitKind string) echo.Middlewa
case "ip":
rateLimitKey = c.RealIP()
case "user":
auth, err := apiv1.GetAuthFromClaims(c)
auth, err := auth2.GetAuthFromClaims(c)
if err != nil {
log.Errorf("Error getting auth from jwt claims: %v", err)
}

View File

@ -53,6 +53,8 @@ import (
"code.vikunja.io/api/pkg/config"
"code.vikunja.io/api/pkg/log"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/modules/auth"
"code.vikunja.io/api/pkg/modules/auth/openid"
"code.vikunja.io/api/pkg/modules/background"
backgroundHandler "code.vikunja.io/api/pkg/modules/background/handler"
"code.vikunja.io/api/pkg/modules/background/unsplash"
@ -165,7 +167,7 @@ func NewEcho() *echo.Echo {
// Handler config
handler.SetAuthProvider(&web.Auths{
AuthObject: apiv1.GetAuthFromClaims,
AuthObject: auth.GetAuthFromClaims,
})
handler.SetLoggingProvider(log.GetLogger())
handler.SetMaxItemsPerPage(config.ServiceMaxItemsPerPage.GetInt())
@ -220,12 +222,18 @@ func registerAPIRoutes(a *echo.Group) {
// Prometheus endpoint
setupMetrics(n)
// User stuff
n.POST("/login", apiv1.Login)
n.POST("/register", apiv1.RegisterUser)
n.POST("/user/password/token", apiv1.UserRequestResetPasswordToken)
n.POST("/user/password/reset", apiv1.UserResetPassword)
n.POST("/user/confirm", apiv1.UserConfirmEmail)
if config.AuthLocalEnabled.GetBool() {
// User stuff
n.POST("/login", apiv1.Login)
n.POST("/register", apiv1.RegisterUser)
n.POST("/user/password/token", apiv1.UserRequestResetPasswordToken)
n.POST("/user/password/reset", apiv1.UserResetPassword)
n.POST("/user/confirm", apiv1.UserConfirmEmail)
}
if config.AuthOpenIDEnabled.GetBool() {
n.POST("/auth/openid/:provider/callback", openid.HandleCallback)
}
// Info endpoint
n.GET("/info", apiv1.Info)