opengist/internal/web/auth.go

415 lines
11 KiB
Go
Raw Normal View History

2023-03-14 15:22:52 +00:00
package web
import (
"context"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"github.com/thomiceli/opengist/internal/utils"
"io"
"net/http"
"net/url"
"strings"
2023-03-14 15:22:52 +00:00
"github.com/labstack/echo/v4"
2023-04-17 17:11:32 +00:00
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
2023-04-17 17:11:32 +00:00
"github.com/markbates/goth/providers/gitea"
"github.com/markbates/goth/providers/github"
2023-12-18 00:35:44 +00:00
"github.com/markbates/goth/providers/gitlab"
2023-09-15 21:56:14 +00:00
"github.com/markbates/goth/providers/openidConnect"
"github.com/rs/zerolog/log"
2023-05-15 19:07:29 +00:00
"github.com/thomiceli/opengist/internal/config"
2023-09-02 22:30:57 +00:00
"github.com/thomiceli/opengist/internal/db"
2023-04-26 21:13:11 +00:00
"golang.org/x/text/cases"
"golang.org/x/text/language"
"gorm.io/gorm"
2023-03-14 15:22:52 +00:00
)
2023-12-18 00:35:44 +00:00
const (
GitHubProvider = "github"
GitLabProvider = "gitlab"
GiteaProvider = "gitea"
OpenIDConnect = "openid-connect"
)
2023-04-26 21:13:11 +00:00
var title = cases.Title(language.English)
2023-03-14 15:22:52 +00:00
func register(ctx echo.Context) error {
2023-09-22 15:26:09 +00:00
setData(ctx, "title", tr(ctx, "auth.new-account"))
2023-03-14 15:22:52 +00:00
setData(ctx, "htmlTitle", "New account")
2023-05-06 16:53:59 +00:00
setData(ctx, "disableForm", getData(ctx, "DisableLoginForm"))
setData(ctx, "isLoginPage", false)
2023-03-14 15:22:52 +00:00
return html(ctx, "auth_form.html")
}
func processRegister(ctx echo.Context) error {
2023-04-28 18:31:10 +00:00
if getData(ctx, "DisableSignup") == true {
2023-03-14 15:22:52 +00:00
return errorRes(403, "Signing up is disabled", nil)
}
2023-05-06 16:53:59 +00:00
if getData(ctx, "DisableLoginForm") == true {
return errorRes(403, "Signing up via registration form is disabled", nil)
}
2023-03-14 15:22:52 +00:00
setData(ctx, "title", "New account")
setData(ctx, "htmlTitle", "New account")
sess := getSession(ctx)
2023-09-02 22:30:57 +00:00
dto := new(db.UserDTO)
2023-03-17 13:56:39 +00:00
if err := ctx.Bind(dto); err != nil {
2023-03-14 15:22:52 +00:00
return errorRes(400, "Cannot bind data", err)
}
2023-03-17 13:56:39 +00:00
if err := ctx.Validate(dto); err != nil {
addFlash(ctx, utils.ValidationMessages(&err), "error")
2023-03-14 15:22:52 +00:00
return html(ctx, "auth_form.html")
}
2023-09-02 22:30:57 +00:00
if exists, err := db.UserExists(dto.Username); err != nil || exists {
2023-03-17 13:56:39 +00:00
addFlash(ctx, "Username already exists", "error")
return html(ctx, "auth_form.html")
}
user := dto.ToUser()
2023-03-14 15:22:52 +00:00
password, err := argon2id.hash(user.Password)
if err != nil {
return errorRes(500, "Cannot hash password", err)
}
user.Password = password
2023-03-17 13:56:39 +00:00
if err = user.Create(); err != nil {
2023-03-14 15:22:52 +00:00
return errorRes(500, "Cannot create user", err)
}
if user.ID == 1 {
2023-03-17 13:56:39 +00:00
if err = user.SetAdmin(); err != nil {
2023-03-14 15:22:52 +00:00
return errorRes(500, "Cannot set user admin", err)
}
}
sess.Values["user"] = user.ID
saveSession(sess, ctx)
return redirect(ctx, "/")
}
func login(ctx echo.Context) error {
2023-09-22 15:26:09 +00:00
setData(ctx, "title", tr(ctx, "auth.login"))
2023-03-14 15:22:52 +00:00
setData(ctx, "htmlTitle", "Login")
2023-05-06 16:53:59 +00:00
setData(ctx, "disableForm", getData(ctx, "DisableLoginForm"))
setData(ctx, "isLoginPage", true)
2023-03-14 15:22:52 +00:00
return html(ctx, "auth_form.html")
}
func processLogin(ctx echo.Context) error {
2023-05-06 16:53:59 +00:00
if getData(ctx, "DisableLoginForm") == true {
return errorRes(403, "Logging in via login form is disabled", nil)
}
2023-03-17 13:56:39 +00:00
var err error
2023-03-14 15:22:52 +00:00
sess := getSession(ctx)
2023-09-02 22:30:57 +00:00
dto := &db.UserDTO{}
2023-03-17 13:56:39 +00:00
if err = ctx.Bind(dto); err != nil {
2023-03-14 15:22:52 +00:00
return errorRes(400, "Cannot bind data", err)
}
2023-03-17 13:56:39 +00:00
password := dto.Password
2023-09-02 22:30:57 +00:00
var user *db.User
2023-03-14 15:22:52 +00:00
2023-09-02 22:30:57 +00:00
if user, err = db.GetUserByUsername(dto.Username); err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return errorRes(500, "Cannot get user", err)
}
log.Warn().Msg("Invalid HTTP authentication attempt from " + ctx.RealIP())
2023-03-14 15:22:52 +00:00
addFlash(ctx, "Invalid credentials", "error")
return redirect(ctx, "/login")
}
if ok, err := argon2id.verify(password, user.Password); !ok {
if err != nil {
return errorRes(500, "Cannot check for password", err)
}
log.Warn().Msg("Invalid HTTP authentication attempt from " + ctx.RealIP())
2023-03-14 15:22:52 +00:00
addFlash(ctx, "Invalid credentials", "error")
return redirect(ctx, "/login")
}
sess.Values["user"] = user.ID
saveSession(sess, ctx)
deleteCsrfCookie(ctx)
return redirect(ctx, "/")
}
func oauthCallback(ctx echo.Context) error {
user, err := gothic.CompleteUserAuth(ctx.Response(), ctx.Request())
if err != nil {
2023-11-20 17:41:01 +00:00
return errorRes(400, "Cannot complete user auth: "+err.Error(), err)
}
currUser := getUserLogged(ctx)
if currUser != nil {
// if user is logged in, link account to user and update its avatar URL
2023-12-18 00:35:44 +00:00
updateUserProviderInfo(currUser, user.Provider, user)
if err = currUser.Update(); err != nil {
2023-04-26 21:13:11 +00:00
return errorRes(500, "Cannot update user "+title.String(user.Provider)+" id", err)
}
2023-04-26 21:13:11 +00:00
addFlash(ctx, "Account linked to "+title.String(user.Provider), "success")
return redirect(ctx, "/settings")
}
// if user is not in database, create it
2023-09-02 22:30:57 +00:00
userDB, err := db.GetUserByProvider(user.UserID, user.Provider)
if err != nil {
2023-04-28 18:31:10 +00:00
if getData(ctx, "DisableSignup") == true {
return errorRes(403, "Signing up is disabled", nil)
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return errorRes(500, "Cannot get user", err)
}
2023-09-02 22:30:57 +00:00
userDB = &db.User{
Username: user.NickName,
Email: user.Email,
MD5Hash: fmt.Sprintf("%x", md5.Sum([]byte(strings.ToLower(strings.TrimSpace(user.Email))))),
}
// set provider id and avatar URL
2023-12-18 00:35:44 +00:00
updateUserProviderInfo(userDB, user.Provider, user)
if err = userDB.Create(); err != nil {
2023-09-02 22:30:57 +00:00
if db.IsUniqueConstraintViolation(err) {
2023-04-17 18:25:35 +00:00
addFlash(ctx, "Username "+user.NickName+" already exists in Opengist", "error")
return redirect(ctx, "/login")
}
return errorRes(500, "Cannot create user", err)
}
if userDB.ID == 1 {
if err = userDB.SetAdmin(); err != nil {
return errorRes(500, "Cannot set user admin", err)
}
}
var resp *http.Response
switch user.Provider {
2023-12-18 00:35:44 +00:00
case GitHubProvider:
resp, err = http.Get("https://github.com/" + user.NickName + ".keys")
2023-12-18 00:35:44 +00:00
case GitLabProvider:
resp, err = http.Get(urlJoin(config.C.GitlabUrl, user.NickName+".keys"))
case GiteaProvider:
resp, err = http.Get(urlJoin(config.C.GiteaUrl, user.NickName+".keys"))
2023-12-18 00:35:44 +00:00
case OpenIDConnect:
2023-09-15 22:48:09 +00:00
err = errors.New("cannot get keys from OIDC provider")
}
if err == nil {
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
addFlash(ctx, "Could not get user keys", "error")
log.Error().Err(err).Msg("Could not get user keys")
}
keys := strings.Split(string(body), "\n")
if len(keys[len(keys)-1]) == 0 {
keys = keys[:len(keys)-1]
}
for _, key := range keys {
2023-09-02 22:30:57 +00:00
sshKey := db.SSHKey{
Title: "Added from " + user.Provider,
Content: key,
User: *userDB,
}
if err = sshKey.Create(); err != nil {
addFlash(ctx, "Could not create ssh key", "error")
log.Error().Err(err).Msg("Could not create ssh key")
}
}
}
}
sess := getSession(ctx)
sess.Values["user"] = userDB.ID
saveSession(sess, ctx)
deleteCsrfCookie(ctx)
return redirect(ctx, "/")
}
func oauth(ctx echo.Context) error {
provider := ctx.Param("provider")
2023-04-17 17:11:32 +00:00
httpProtocol := "http"
if ctx.Request().TLS != nil || ctx.Request().Header.Get("X-Forwarded-Proto") == "https" {
httpProtocol = "https"
}
2023-04-30 10:09:42 +00:00
var opengistUrl string
if config.C.ExternalUrl != "" {
opengistUrl = config.C.ExternalUrl
} else {
opengistUrl = httpProtocol + "://" + ctx.Request().Host
}
2023-04-17 17:11:32 +00:00
switch provider {
2023-12-18 00:35:44 +00:00
case GitHubProvider:
2023-04-17 17:11:32 +00:00
goth.UseProviders(
github.New(
config.C.GithubClientKey,
config.C.GithubSecret,
2023-05-29 20:39:30 +00:00
urlJoin(opengistUrl, "/oauth/github/callback"),
),
2023-04-17 17:11:32 +00:00
)
2023-12-18 00:35:44 +00:00
case GitLabProvider:
goth.UseProviders(
gitlab.NewCustomisedURL(
config.C.GitlabClientKey,
config.C.GitlabSecret,
urlJoin(opengistUrl, "/oauth/gitlab/callback"),
urlJoin(config.C.GitlabUrl, "/oauth/authorize"),
urlJoin(config.C.GitlabUrl, "/oauth/token"),
urlJoin(config.C.GitlabUrl, "/api/v4/user"),
),
)
case GiteaProvider:
2023-04-17 17:11:32 +00:00
goth.UseProviders(
gitea.NewCustomisedURL(
config.C.GiteaClientKey,
config.C.GiteaSecret,
2023-05-29 20:39:30 +00:00
urlJoin(opengistUrl, "/oauth/gitea/callback"),
urlJoin(config.C.GiteaUrl, "/login/oauth/authorize"),
urlJoin(config.C.GiteaUrl, "/login/oauth/access_token"),
urlJoin(config.C.GiteaUrl, "/api/v1/user"),
),
2023-04-17 17:11:32 +00:00
)
2023-12-18 00:35:44 +00:00
case OpenIDConnect:
2023-09-15 21:56:14 +00:00
oidcProvider, err := openidConnect.New(
config.C.OIDCClientKey,
config.C.OIDCSecret,
urlJoin(opengistUrl, "/oauth/openid-connect/callback"),
config.C.OIDCDiscoveryUrl,
"openid",
"email",
"profile",
)
if err != nil {
return errorRes(500, "Cannot create OIDC provider", err)
}
goth.UseProviders(oidcProvider)
2023-04-17 17:11:32 +00:00
}
currUser := getUserLogged(ctx)
if currUser != nil {
2023-12-18 00:35:44 +00:00
// Map each provider to a function that checks the relevant ID in currUser
providerIDCheckMap := map[string]func() bool{
GitHubProvider: func() bool { return currUser.GithubID != "" },
GitLabProvider: func() bool { return currUser.GitlabID != "" },
GiteaProvider: func() bool { return currUser.GiteaID != "" },
OpenIDConnect: func() bool { return currUser.OIDCID != "" },
}
2023-12-18 00:35:44 +00:00
// Check if the provider is valid and if the user has a linked ID
// Means that the user wants to unlink the account
if checkFunc, exists := providerIDCheckMap[provider]; exists && checkFunc() {
if err := currUser.DeleteProviderID(provider); err != nil {
return errorRes(500, "Cannot unlink account from "+title.String(provider), err)
}
2023-04-26 21:13:11 +00:00
addFlash(ctx, "Account unlinked from "+title.String(provider), "success")
return redirect(ctx, "/settings")
}
}
2023-04-28 18:31:10 +00:00
ctxValue := context.WithValue(ctx.Request().Context(), gothic.ProviderParamKey, provider)
ctx.SetRequest(ctx.Request().WithContext(ctxValue))
2023-12-18 00:35:44 +00:00
if provider != GitHubProvider && provider != GitLabProvider && provider != GiteaProvider && provider != OpenIDConnect {
return errorRes(400, "Unsupported provider", nil)
}
gothic.BeginAuthHandler(ctx.Response(), ctx.Request())
return nil
}
2023-03-14 15:22:52 +00:00
func logout(ctx echo.Context) error {
deleteSession(ctx)
deleteCsrfCookie(ctx)
return redirect(ctx, "/all")
}
2023-04-17 19:31:40 +00:00
2023-05-29 20:39:30 +00:00
func urlJoin(base string, elem ...string) string {
joined, err := url.JoinPath(base, elem...)
if err != nil {
log.Error().Err(err).Msg("Cannot join url")
}
return joined
}
2023-12-18 00:35:44 +00:00
func updateUserProviderInfo(userDB *db.User, provider string, user goth.User) {
userDB.AvatarURL = getAvatarUrlFromProvider(provider, user.UserID)
switch provider {
case GitHubProvider:
userDB.GithubID = user.UserID
case GitLabProvider:
userDB.GitlabID = user.UserID
case GiteaProvider:
userDB.GiteaID = user.UserID
case OpenIDConnect:
userDB.OIDCID = user.UserID
userDB.AvatarURL = user.AvatarURL
}
}
func getAvatarUrlFromProvider(provider string, identifier string) string {
switch provider {
2023-12-18 00:35:44 +00:00
case GitHubProvider:
return "https://avatars.githubusercontent.com/u/" + identifier + "?v=4"
2023-12-18 00:35:44 +00:00
case GitLabProvider:
return urlJoin(config.C.GitlabUrl, "/uploads/-/system/user/avatar/", identifier, "/avatar.png") + "?width=400"
case GiteaProvider:
resp, err := http.Get(urlJoin(config.C.GiteaUrl, "/api/v1/users/", identifier))
if err != nil {
log.Error().Err(err).Msg("Cannot get user from Gitea")
return ""
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Error().Err(err).Msg("Cannot read Gitea response body")
return ""
}
var result map[string]interface{}
err = json.Unmarshal(body, &result)
if err != nil {
log.Error().Err(err).Msg("Cannot unmarshal Gitea response body")
return ""
}
field, ok := result["avatar_url"]
if !ok {
log.Error().Msg("Field 'avatar_url' not found in Gitea JSON response")
return ""
}
return field.(string)
}
return ""
}