-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathlogin.go
More file actions
831 lines (688 loc) · 19.2 KB
/
login.go
File metadata and controls
831 lines (688 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
package api
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"sort"
"strings"
"text/template"
"time"
"github.com/semaphoreui/semaphore/pkg/tz"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-ldap/ldap/v3"
"github.com/gorilla/mux"
"github.com/semaphoreui/semaphore/api/helpers"
"github.com/semaphoreui/semaphore/db"
"github.com/semaphoreui/semaphore/pkg/random"
"github.com/semaphoreui/semaphore/util"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
"golang.org/x/oauth2"
)
func convertEntryToMap(entity *ldap.Entry) map[string]any {
res := map[string]any{}
for _, attr := range entity.Attributes {
if len(attr.Values) == 0 {
continue
}
res[attr.Name] = attr.Values[0]
}
return res
}
func tryFindLDAPUser(username, password string) (*db.User, error) {
if !util.Config.LdapEnable {
return nil, fmt.Errorf("LDAP not configured")
}
var l *ldap.Conn
var err error
if util.Config.LdapNeedTLS {
l, err = ldap.DialTLS("tcp", util.Config.LdapServer, &tls.Config{
InsecureSkipVerify: true,
})
} else {
l, err = ldap.Dial("tcp", util.Config.LdapServer)
}
if err != nil {
return nil, err
}
defer l.Close() //nolint:errcheck
// First bind with a read only user
if err = l.Bind(util.Config.LdapBindDN, util.Config.LdapBindPassword); err != nil {
return nil, err
}
// Filter for the given username
searchRequest := ldap.NewSearchRequest(
util.Config.LdapSearchDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf(util.Config.LdapSearchFilter, username),
[]string{util.Config.LdapMappings.DN},
nil,
)
sr, err := l.Search(searchRequest)
if err != nil {
return nil, err
}
if len(sr.Entries) < 1 {
return nil, nil
}
if len(sr.Entries) > 1 {
return nil, fmt.Errorf("too many entries returned")
}
// Bind as the user
userDN := sr.Entries[0].DN
if err = l.Bind(userDN, password); err != nil {
return nil, err
}
// Second time bind as read only user
if err = l.Bind(util.Config.LdapBindDN, util.Config.LdapBindPassword); err != nil {
return nil, err
}
// Get user info
searchRequest = ldap.NewSearchRequest(
util.Config.LdapSearchDN,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf(util.Config.LdapSearchFilter, username),
[]string{util.Config.LdapMappings.DN, util.Config.LdapMappings.Mail, util.Config.LdapMappings.UID, util.Config.LdapMappings.CN},
nil,
)
sr, err = l.Search(searchRequest)
if err != nil {
return nil, err
}
if len(sr.Entries) <= 0 {
return nil, fmt.Errorf("ldap search returned no entries")
}
entry := convertEntryToMap(sr.Entries[0])
prepareClaims(entry)
claims, err := parseClaims(entry, util.Config.LdapMappings)
if err != nil {
return nil, err
}
ldapUser := db.User{
Username: strings.ToLower(claims.username),
Created: tz.Now(),
Name: claims.name,
Email: claims.email,
External: true,
Alert: false,
}
err = db.ValidateUser(ldapUser)
if err != nil {
jsonBytes, _ := json.Marshal(ldapUser)
log.Error("LDAP returned incorrect user data: " + string(jsonBytes))
return nil, err
}
log.Info("User " + ldapUser.Name + " with email " + ldapUser.Email + " authorized via LDAP correctly")
return &ldapUser, nil
}
// createSession creates session for passed user and stores session details
// in cookies.
func createSession(w http.ResponseWriter, r *http.Request, user db.User, oidc bool) {
var err error
var verificationMethod db.SessionVerificationMethod
verified := false
switch {
case user.Totp != nil && util.Config.Auth.Totp.Enabled:
verificationMethod = db.SessionVerificationTotp
default:
verificationMethod = db.SessionVerificationNone
verified = true
}
newSession, err := helpers.Store(r).CreateSession(db.Session{
UserID: user.ID,
Created: tz.Now(),
LastActive: tz.Now(),
IP: r.Header.Get("X-Real-IP"),
UserAgent: r.Header.Get("user-agent"),
Expired: false,
VerificationMethod: verificationMethod,
Verified: verified,
})
if err != nil {
log.WithError(err).WithFields(log.Fields{
"user_id": user.ID,
"context": "session",
}).Error("Failed to create session")
helpers.WriteErrorStatus(w, "Failed to create session", http.StatusInternalServerError)
return
}
encoded, err := util.Cookie.Encode("semaphore", map[string]any{
"user": user.ID,
"session": newSession.ID,
})
if err != nil {
log.WithError(err).WithFields(log.Fields{
"user_id": user.ID,
"context": "session",
}).Error("Failed to encode session cookie")
helpers.WriteErrorStatus(w, "Failed to create session", http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{
Name: "semaphore",
Value: encoded,
Path: "/",
HttpOnly: true,
})
}
func loginByPassword(store db.Store, login string, password string) (user db.User, err error) {
user, err = store.GetUserByLoginOrEmail(login, login)
if err != nil {
return
}
if user.External {
err = db.ErrNotFound
return
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil {
err = db.ErrNotFound
return
}
return
}
func loginByLDAP(store db.Store, ldapUser db.User) (user db.User, err error) {
user, err = store.GetUserByLoginOrEmail(ldapUser.Username, ldapUser.Email)
if errors.Is(err, db.ErrNotFound) {
user, err = store.CreateUserWithoutPassword(ldapUser)
}
if err != nil {
return
}
if !user.External {
err = db.ErrNotFound
return
}
return
}
type loginMetadataOidcProvider struct {
ID string `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
Icon string `json:"icon"`
}
type LoginTotpAuthMethod struct {
AllowRecovery bool `json:"allow_recovery"`
}
type LoginEmailAuthMethod struct {
}
type LoginAuthMethods struct {
Totp *LoginTotpAuthMethod `json:"totp,omitempty"`
Email *LoginEmailAuthMethod `json:"email,omitempty"`
}
type loginMetadata struct {
OidcProviders []loginMetadataOidcProvider `json:"oidc_providers"`
LoginWithPassword bool `json:"login_with_password"`
AuthMethods LoginAuthMethods `json:"auth_methods"`
}
// nolint: gocyclo
func login(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
config := &loginMetadata{
OidcProviders: make([]loginMetadataOidcProvider, len(util.Config.OidcProviders)),
LoginWithPassword: !util.Config.PasswordLoginDisable,
}
i := 0
for k, v := range util.Config.OidcProviders {
config.OidcProviders[i] = loginMetadataOidcProvider{
ID: k,
Name: v.DisplayName,
Color: v.Color,
Icon: v.Icon,
}
i++
}
sort.Slice(config.OidcProviders, func(i, j int) bool {
a := util.Config.OidcProviders[config.OidcProviders[i].ID]
b := util.Config.OidcProviders[config.OidcProviders[j].ID]
return a.Order < b.Order
})
if util.Config.Auth.Totp.Enabled {
config.AuthMethods.Totp = &LoginTotpAuthMethod{
AllowRecovery: util.Config.Auth.Totp.AllowRecovery,
}
}
helpers.WriteJSON(w, http.StatusOK, config)
return
}
var login struct {
Auth string `json:"auth" binding:"required"`
Password string `json:"password" binding:"required"`
}
if !helpers.Bind(w, r, &login) {
return
}
/*
logic:
- fetch user from ldap if enabled
- fetch user from database by username/email
- create user in database if doesn't exist & ldap record found
- check password if non-ldap user
- create session & send cookie
*/
login.Auth = strings.ToLower(login.Auth)
var err error
var ldapUser *db.User
if util.Config.LdapEnable {
ldapUser, err = tryFindLDAPUser(login.Auth, login.Password)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"context": "ldap",
"auth": login.Auth,
}).Warn("Failed to find user in LDAP")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
var user db.User
if ldapUser == nil {
user, err = loginByPassword(helpers.Store(r), login.Auth, login.Password)
} else {
user, err = loginByLDAP(helpers.Store(r), *ldapUser)
}
if err != nil {
if errors.Is(err, db.ErrNotFound) {
w.WriteHeader(http.StatusUnauthorized)
return
}
var validationError *db.ValidationError
switch {
case errors.As(err, &validationError):
// TODO: Return more informative error code.
}
log.Error(err.Error())
w.WriteHeader(http.StatusInternalServerError)
}
createSession(w, r, user, false)
w.WriteHeader(http.StatusNoContent)
}
// logout handles the user logout process by expiring the current session
// and clearing the session cookie.
//
// Behavior:
// - If a valid session exists, it is expired in the database.
// - The session cookie is cleared by setting its value to an empty string
// and its expiration date to a past time.
//
// Responses:
// - 204 No Content: Logout successful.
// - 500 Internal Server Error: An error occurred while expiring the session.
func logout(w http.ResponseWriter, r *http.Request) {
if session, ok := getSession(r); ok {
err := helpers.Store(r).ExpireSession(session.UserID, session.ID)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
http.SetCookie(w, &http.Cookie{
Name: "semaphore",
Value: "",
Expires: tz.Now().Add(24 * 7 * time.Hour * -1),
Path: "/",
HttpOnly: true,
})
w.WriteHeader(http.StatusNoContent)
}
func getOidcProvider(id string, ctx context.Context, redirectPath string) (*oidc.Provider, *oauth2.Config, error) {
provider, ok := util.Config.OidcProviders[id]
if !ok {
return nil, nil, fmt.Errorf("no such provider: %s", id)
}
config := oidc.ProviderConfig{
IssuerURL: provider.Endpoint.IssuerURL,
AuthURL: provider.Endpoint.AuthURL,
TokenURL: provider.Endpoint.TokenURL,
UserInfoURL: provider.Endpoint.UserInfoURL,
JWKSURL: provider.Endpoint.JWKSURL,
Algorithms: provider.Endpoint.Algorithms,
}
oidcProvider := config.NewProvider(ctx)
var err error
if provider.AutoDiscovery != "" {
oidcProvider, err = oidc.NewProvider(ctx, provider.AutoDiscovery)
if err != nil {
return nil, nil, err
}
}
clientID := provider.ClientID
if provider.ClientIDFile != "" {
if clientID, err = getSecretFromFile(provider.ClientIDFile); err != nil {
return nil, nil, err
}
}
clientSecret := provider.ClientSecret
if provider.ClientSecretFile != "" {
if clientSecret, err = getSecretFromFile(provider.ClientSecretFile); err != nil {
return nil, nil, err
}
}
if redirectPath != "" {
redirectPath = strings.TrimRight(redirectPath, "/")
providerUrl, err2 := url.Parse(provider.RedirectURL)
if err2 != nil {
return nil, nil, err2
}
providerPath := strings.TrimRight(providerUrl.Path, "/")
if redirectPath == providerPath {
redirectPath = ""
} else if strings.HasPrefix(redirectPath, providerPath+"/") {
redirectPath = redirectPath[len(providerPath):]
}
}
oauthConfig := oauth2.Config{
Endpoint: oidcProvider.Endpoint(),
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: provider.RedirectURL + redirectPath,
Scopes: provider.Scopes,
}
if len(oauthConfig.RedirectURL) == 0 {
redirectURL, err := url.JoinPath(util.Config.WebHost, "api/auth/oidc", id, "redirect")
if err != nil {
return nil, nil, err
}
oauthConfig.RedirectURL = redirectURL
if redirectURL != redirectPath {
oauthConfig.RedirectURL += redirectPath
}
}
if len(oauthConfig.Scopes) == 0 {
oauthConfig.Scopes = []string{"openid", "profile", "email"}
}
return oidcProvider, &oauthConfig, nil
}
func oidcLogin(w http.ResponseWriter, r *http.Request) {
pid := mux.Vars(r)["provider"]
ctx := context.Background()
loginURL, _ := url.JoinPath(util.Config.WebHost, "auth/login")
returnPath := ""
redirectPath := ""
config, ok := util.Config.OidcProviders[pid]
if !ok {
log.Error(fmt.Errorf("no such provider: %s", pid))
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
returnValue := r.URL.Query().Get("return")
if returnValue != "" {
if config.ReturnViaState {
returnPath = returnValue
} else {
redirectPath = returnValue
}
}
_, oauth, err := getOidcProvider(pid, ctx, redirectPath)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
state := generateStateOauthCookie(w, returnPath)
u := oauth.AuthCodeURL(state)
http.Redirect(w, r, u, http.StatusTemporaryRedirect)
}
type oAuthState struct {
Csrf string `json:"csrf"`
Return string `json:"return"`
}
func generateStateOauthCookie(w http.ResponseWriter, returnPath string) string {
expiration := tz.Now().Add(365 * 24 * time.Hour)
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
state := oAuthState{
Csrf: base64.URLEncoding.EncodeToString(b),
Return: returnPath,
}
// Secure flag is not set to allow Semaphore to be used without HTTPS inside private networks
cookie := http.Cookie{
Name: "oauthstate",
Value: state.Csrf,
Expires: expiration,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
http.SetCookie(w, &cookie)
stateBytes, err := json.Marshal(state)
if err != nil {
panic(err)
}
return base64.URLEncoding.EncodeToString(stateBytes)
}
type claimResult struct {
username string
name string
email string
}
func parseClaim(str string, claims map[string]any) (string, bool) {
for _, s := range strings.Split(str, "|") {
s = strings.TrimSpace(s)
if s == "" {
continue
}
if strings.Contains(s, "{{") {
tpl, err := template.New("").Parse(s)
if err != nil {
return "", false
}
buff := bytes.NewBufferString("")
if err = tpl.Execute(buff, claims); err != nil {
return "", false
}
res := buff.String()
return res, res != ""
}
res, ok := claims[s].(string)
if res != "" && ok {
return res, ok
}
}
return "", false
}
func prepareClaims(claims map[string]any) {
for k, v := range claims {
switch v := v.(type) {
case float64:
f := v
i := int64(f)
if float64(i) == f {
claims[k] = i
}
case float32:
f := v
i := int64(f)
if float32(i) == f {
claims[k] = i
}
}
}
}
func parseClaims(claims map[string]any, provider util.ClaimsProvider) (res claimResult, err error) {
var ok bool
res.email, ok = parseClaim(provider.GetEmailClaim(), claims)
if !ok {
err = fmt.Errorf("claim '%s' missing or has bad format", provider.GetEmailClaim())
return
}
res.username, ok = parseClaim(provider.GetUsernameClaim(), claims)
if !ok {
res.username = getRandomUsername()
}
res.name, ok = parseClaim(provider.GetNameClaim(), claims)
if !ok {
res.name = getRandomProfileName()
}
return
}
func claimOidcUserInfo(userInfo *oidc.UserInfo, provider util.OidcProvider) (res claimResult, err error) {
claims := make(map[string]any)
if err = userInfo.Claims(&claims); err != nil {
return
}
prepareClaims(claims)
return parseClaims(claims, &provider)
}
func claimOidcToken(idToken *oidc.IDToken, provider util.OidcProvider) (res claimResult, err error) {
claims := make(map[string]any)
if err = idToken.Claims(&claims); err != nil {
return
}
prepareClaims(claims)
return parseClaims(claims, &provider)
}
func getRandomUsername() string {
return random.String(16)
}
func getRandomProfileName() string {
return "Anonymous"
}
func getSecretFromFile(source string) (string, error) {
content, err := os.ReadFile(source)
if err != nil {
return "", err
}
return string(content), nil
}
func oidcRedirect(w http.ResponseWriter, r *http.Request) {
pid := mux.Vars(r)["provider"]
loginURL, _ := url.JoinPath(util.Config.WebHost, "auth/login")
provider, ok := util.Config.OidcProviders[pid]
if !ok {
log.Error(fmt.Errorf("no such provider: %s", pid))
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
// IdP-initiated flow is detected by the absence of a state parameter.
// In SP-initiated flow, oidcLogin always sets state before redirecting to the IdP.
stateParam := r.FormValue("state")
idpInitiated := stateParam == ""
var stateData oAuthState
if idpInitiated {
if !provider.AllowIdpInitiated {
log.Warn("IdP-initiated OIDC login attempted but not allowed for provider: " + pid)
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
} else {
oauthState, err := r.Cookie("oauthstate")
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
b, err := base64.URLEncoding.DecodeString(stateParam)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
if err = json.Unmarshal(b, &stateData); err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
if stateData.Csrf != oauthState.Value {
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
}
ctx := context.Background()
_oidc, oauth, err := getOidcProvider(pid, ctx, r.URL.Path)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
verifier := _oidc.Verifier(&oidc.Config{ClientID: oauth.ClientID})
code := r.URL.Query().Get("code")
oauth2Token, err := oauth.Exchange(ctx, code)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
var claims claimResult
rawIDToken, tokenOk := oauth2Token.Extra("id_token").(string)
if tokenOk && rawIDToken != "" {
var idToken *oidc.IDToken
idToken, err = verifier.Verify(ctx, rawIDToken)
if err == nil {
claims, err = claimOidcToken(idToken, provider)
}
} else {
var userInfo *oidc.UserInfo
userInfo, err = _oidc.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
if err == nil {
if userInfo.Email == "" {
claims, err = claimOidcUserInfo(userInfo, provider)
} else {
claims.email = userInfo.Email
claims.name = userInfo.Profile
}
}
claims.username = getRandomUsername()
if userInfo.Profile == "" {
claims.name = getRandomProfileName()
}
}
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
user, err := helpers.Store(r).GetUserByLoginOrEmail("", claims.email)
if err != nil {
user = db.User{
Username: claims.username,
Name: claims.name,
Email: claims.email,
External: true,
Pro: true,
}
user, err = helpers.Store(r).CreateUserWithoutPassword(user)
if err != nil {
log.Error(err.Error())
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
}
if !user.External {
log.Error(fmt.Errorf("OIDC user '%s' conflicts with local user", user.Username))
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
createSession(w, r, user, true)
redirectPath := ""
if !idpInitiated {
if provider.ReturnViaState {
redirectPath = stateData.Return
} else {
redirectPath = mux.Vars(r)["redirect_path"]
}
}
if !strings.HasPrefix(redirectPath, "/") {
redirectPath = "/" + redirectPath
}
redirectURL, err := url.JoinPath(util.Config.WebHost, redirectPath)
if err != nil {
log.Error(err)
http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect)
return
}
if redirectURL == "" {
redirectURL = "/"
}
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
}