aboutsummaryrefslogtreecommitdiff
path: root/session.go
blob: 0867b16f0b7a778010956ff84364640684eeae70 (plain)
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
package main


import (
	"fmt"
	"net/http"												 
	"bufio"													 
	"os"
	"strings"	
	"github.com/gomodule/redigo/redis"
)

var cache redis.Conn

func InitCache() {
	conn, err := redis.DialURL("redis://localhost")
	if err != nil {
		panic(err)
	}
	cache = conn
}

func CheckSession(w http.ResponseWriter, r *http.Request) (interface{}, error){

	c, err := r.Cookie("session_token")

	if err != nil {
		if err == http.ErrNoCookie {
			w.WriteHeader(http.StatusUnauthorized)
			return nil, err
		}
		
		w.WriteHeader(http.StatusBadRequest)
		return nil, err
	}
	
	sessionToken := c.Value

	response, err := cache.Do("GET", sessionToken)
	
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return nil, err
	}
	if response == nil {
		w.WriteHeader(http.StatusUnauthorized)
		return nil, err
	}

	return response, nil
}

func GetClientKey() string{
	file, err := os.Open("clientkey")

	CheckError(err, "could not open client key in file")

	defer file.Close()

	scanner := bufio.NewScanner(file)
	var line string
	for scanner.Scan() {
		line = fmt.Sprintf("%s", scanner.Text())
	}

	return line
}

func GetPasswordFromSession(r *http.Request) (string, string) {

	c, err := r.Cookie("session_token")

	if err != nil {
		return "", ""
	}

	sessionToken := c.Value

	response, err := cache.Do("GET", sessionToken)

	if CheckError(err, "could not get session from cache") != nil {
		return "", ""
	}

	token := fmt.Sprintf("%s", response)

	parts := strings.Split(token, "|")

	if len(parts) > 1 {
		return parts[0], parts[1]
	}

	return "", ""
}