forked from fnproject/fn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
90 lines (72 loc) · 1.55 KB
/
function.go
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
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/fnproject/fn/examples/blog/database"
"github.com/fnproject/fn/examples/blog/models"
"github.com/fnproject/fn/examples/blog/routes"
)
var noAuth = map[string]interface{}{}
func main() {
request := fmt.Sprintf("%s %s", os.Getenv("FN_METHOD"), os.Getenv("FN_PATH"))
dbURI := os.Getenv("DB")
if dbURI == "" {
dbURI = "127.0.0.1/blog"
}
db := database.New(dbURI)
if created := createUser(db); created {
return
}
// PUBLIC REQUESTS
switch request {
case "GET /posts":
route.HandlePostList(db, noAuth)
return
case "GET /posts/:id":
route.HandlePostRead(db, noAuth)
return
}
// GETTING TOKEN
if os.Getenv("FN_PATH") == "/token" {
route.HandleToken(db)
return
}
// AUTHENTICATION
auth, valid := route.Authentication()
if !valid {
route.SendError("Invalid authentication")
return
}
// AUTHENTICATED ONLY REQUESTS
if request == "POST /posts" {
route.HandlePostCreate(db, auth)
return
}
route.SendError("Not found")
}
func createUser(db *database.Database) bool {
env := os.Getenv("NEWUSER")
if env == "" {
return false
}
var user *models.User
err := json.Unmarshal([]byte(env), &user)
if err != nil {
fmt.Println(err)
return true
}
if user.Username == "" || user.NewPassword == "" {
fmt.Println("missing username or password")
return true
}
user.Password = []byte(user.NewPassword)
user.NewPassword = ""
user, err = db.SaveUser(user)
if err != nil {
fmt.Println("couldn't create user")
} else {
fmt.Println("user created")
}
return true
}