DEVELOPMENT ENVIRONMENT

~liljamo/tixe

ref: 52cbe7fcff843ec176f978d8ca54b18b2173dd27 tixe/handlers/authlogin.go -rw-r--r-- 948 bytes
52cbe7fcJonni Liljamo fix: better example compose 1 year, 1 month ago
                                                                                
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
/*
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */
package handlers

import (
	"crypto/rand"
	"encoding/base64"
	"net/http"
	"tixe/auth"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func AuthLogin(auth *auth.Auth) gin.HandlerFunc {
	return func(c *gin.Context) {
		state, err := randomState()
		if err != nil {
			c.String(http.StatusInternalServerError, err.Error())
			return
		}

		session := sessions.Default(c)
		session.Set("state", state)
		if err := session.Save(); err != nil {
			c.String(http.StatusInternalServerError, err.Error())
			return
		}

		c.Redirect(http.StatusTemporaryRedirect, auth.AuthCodeURL(state))
	}
}

func randomState() (string, error) {
	buf := make([]byte, 32)
	_, err := rand.Read(buf)
	if err != nil {
		return "", nil
	}

	return base64.StdEncoding.EncodeToString(buf), nil
}