File: server.go

package info (click to toggle)
golang-github-yohcop-openid-go 0.0~git20170901.0.cfc72ed-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 184 kB
  • sloc: makefile: 3
file content (75 lines) | stat: -rw-r--r-- 1,937 bytes parent folder | download | duplicates (4)
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 main

import (
	"github.com/yohcop/openid-go"
	"html/template"
	"log"
	"net/http"
)

const dataDir = "_example/"

// For the demo, we use in-memory infinite storage nonce and discovery
// cache. In your app, do not use this as it will eat up memory and never
// free it. Use your own implementation, on a better database system.
// If you have multiple servers for example, you may need to share at least
// the nonceStore between them.
var nonceStore = openid.NewSimpleNonceStore()
var discoveryCache = openid.NewSimpleDiscoveryCache()

func indexHandler(w http.ResponseWriter, r *http.Request) {
	p := make(map[string]string)
	if t, err := template.ParseFiles(dataDir + "index.html"); err == nil {
		t.Execute(w, p)
	} else {
		log.Print(err)
	}
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
	p := make(map[string]string)
	if t, err := template.ParseFiles(dataDir + "login.html"); err == nil {
		t.Execute(w, p)
	} else {
		log.Print(err)
	}
}

func discoverHandler(w http.ResponseWriter, r *http.Request) {
	if url, err := openid.RedirectURL(r.FormValue("id"),
		"http://localhost:8080/openidcallback",
		"http://localhost:8080/"); err == nil {
		http.Redirect(w, r, url, 303)
	} else {
		log.Print(err)
	}
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	fullUrl := "http://localhost:8080" + r.URL.String()
	log.Print(fullUrl)
	id, err := openid.Verify(
		fullUrl,
		discoveryCache, nonceStore)
	if err == nil {
		p := make(map[string]string)
		p["user"] = id
		if t, err := template.ParseFiles(dataDir + "index.html"); err == nil {
			t.Execute(w, p)
		} else {
			log.Println("WTF")
			log.Print(err)
		}
	} else {
		log.Println("WTF2")
		log.Print(err)
	}
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/login", loginHandler)
	http.HandleFunc("/discover", discoverHandler)
	http.HandleFunc("/openidcallback", callbackHandler)
	http.ListenAndServe(":8080", nil)
}