aboutsummaryrefslogtreecommitdiff
path: root/backend/controllers/controllers.go
blob: a24fc3c475f495b4bf7414eef95952231af068d0 (plain) (blame)
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
package controllers

import (
	"log"
	"net/http"

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

func Home(c *gin.Context) {
	session := sessions.Default(c)
	if session.Get("id") == nil {
		c.JSON(200, "no id, not auth")
	} else {
		var user *steam_go.PlayerSummaries
		user, err := steam_go.GetPlayerSummaries(session.Get("id").(string), GetEnvKey("API_KEY"))
		if err != nil {
			c.JSON(200, "authenticated, but err")
			log.Panic(err)
		} else {
			c.JSON(200, gin.H{
				"output": user,
			})
		}
	}
}

func Login(c *gin.Context) {
	opId := steam_go.NewOpenId(c.Request)
	switch opId.Mode() {
	case "":
		http.Redirect(c.Writer, c.Request, opId.AuthUrl(), 301)
	case "cancel":
		c.Writer.Write([]byte("Authorization cancelled"))
	default:
		steamId, err := opId.ValidateAndGetId()
		if err != nil {
			http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
		}
		session := sessions.Default(c)
		session.Set("id", steamId)
		session.Save()
		// Do whatever you want with steam id
		c.Redirect(http.StatusMovedPermanently, "/")
		c.Writer.Write([]byte(steamId))
	}
}

func Logout(c *gin.Context) {
	session := sessions.Default(c)
	if session.Get("id") == nil {
		c.JSON(http.StatusBadRequest, "no id, not auth")
	} else {
		session.Set("id", "")
		session.Clear()
		session.Options(sessions.Options{Path: "/", MaxAge: -1})
		session.Save()
		log.Print("id", session.Get("id"))
		c.Redirect(http.StatusPermanentRedirect, "/")
	}
}