DEVELOPMENT ENVIRONMENT

~liljamo/tixe

ref: internal-users-1st-draft tixe/handlers/auth.go -rw-r--r-- 2.1 KiB
c57a862cJonni Liljamo wip: internal users 1 year, 3 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
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
package handlers

import (
	"context"
	"log"
	"net/http"
	"tixe/auth"
	"tixe/db"

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

func AuthCallback(auth *auth.Auth) gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		if c.Query("state") != session.Get("state") {
			c.String(http.StatusBadRequest, "Invalid state parameter!")
			return
		}

		token, err := auth.Exchange(c.Request.Context(), c.Query("code"))
		if err != nil {
			c.String(http.StatusUnauthorized, "Failed to exchange authorization code for token!")
			return
		}

		idToken, err := auth.VerifyIDToken(c.Request.Context(), token)
		if err != nil {
			c.String(http.StatusInternalServerError, "Failed to verify ID token!")
			return
		}

		var profile map[string]interface{}
		if err := idToken.Claims(&profile); err != nil {
			c.String(http.StatusInternalServerError, err.Error())
			return
		}

		session.Set("access_token", token.AccessToken)
		session.Set("profile", profile)
		if err := session.Save(); err != nil {
			c.String(http.StatusInternalServerError, err.Error())
			return
		}

		// Create a user in the database for this OIDC user.
		// idToken.Subject shooooould be unique and always the same for a user.
		// I think. Maybe.

		// But first, check if it exists!
		var oidcSubject string
		err = db.PgPool.QueryRow(context.Background(), "SELECT oidc_subject FROM users WHERE oidc_subject = $1", idToken.Subject).Scan(&oidcSubject)
		if err != nil {
			log.Printf("[tixe/auth] WARN: Failed to query database for oidc user")
			c.String(http.StatusInternalServerError, err.Error())
			return
		}
		if idToken.Subject == oidcSubject {
			// Exists, we outta here!
			c.Redirect(http.StatusTemporaryRedirect, "/")
			return
		}

		// Now create it, since it did not exists.
		_, err = db.PgPool.Exec(context.Background(), "INSERT INTO users(display_name, oidc_subject) VALUES($1, $2)", profile["name"].(string), idToken.Subject)
		if err != nil {
			log.Printf("[tixe/auth] WARN: Could not create database entry for oidc user.")
			c.String(http.StatusInternalServerError, err.Error())
			return
		}

		c.Redirect(http.StatusTemporaryRedirect, "/")
	}
}