DEVELOPMENT ENVIRONMENT

~liljamo/tixe

ref: 0.1.0 tixe/handlers/authlogin.go -rw-r--r-- 948 bytes
2038e2d0Jonni Liljamo feat: first ci attempt 11 months 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
}