/
main.go
187 lines (153 loc) · 4.42 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"html/template"
"github.com/gorilla/sessions"
"github.com/gorilla/websocket"
_ "github.com/lean-enjoyers/catchat/pkg/command/commands"
"github.com/lean-enjoyers/catchat/pkg/domain"
)
func getTemplates() *template.Template {
t := template.Must(template.ParseGlob("tmpl/*.html"))
template.Must(t.ParseGlob("tmpl/base/*.html"))
return t
}
func setupRoutes(hub *domain.Hub, options *domain.Conf) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
serveIndex(options, w, r)
})
http.HandleFunc("/say", serve)
http.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
serveWs(hub, w, r)
})
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/sign-up", registerHandler)
}
func serve(w http.ResponseWriter, r *http.Request) {
reqBody, _ := ioutil.ReadAll(r.Body)
arg := string(reqBody)
cmd := exec.Command("catdream", arg)
stdout, err := cmd.Output()
if err != nil {
return
}
fmt.Fprintf(w, string(stdout))
}
func serveIndex(options *domain.Conf, w http.ResponseWriter, r *http.Request) {
err := templates.ExecuteTemplate(w, "baseHTML", map[string]interface{}{
"port": options.Port,
})
if err != nil {
log.Print(err)
}
}
// Serve web sockets
func serveWs(hub *domain.Hub, w http.ResponseWriter, r *http.Request) {
// Allow all origins
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := domain.MakeClient(conn)
// Select the hub to connect to.
client.SelectHub(hub)
// Connect the client to the hub.
client.Connect()
go client.SendLoop()
go client.ReceiveLoop()
}
///////////////////////////////
// Note(Appy): Authentication
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method Not Supported", http.StatusMethodNotAllowed)
return
}
err := r.ParseForm()
if err != nil {
http.Error(w, "Please pass the data as URL form encoded", http.StatusBadRequest)
return
}
// Retrieve username and password from the form
username := r.Form.Get("username")
password := r.Form.Get("password")
pswd, exists := users[username]
if exists {
// Returns a new session if there is no current session.
session, _ := store.Get(r, "session.id")
if pswd == password {
session.Values["authenticated"] = true
session.Save(r, w)
} else {
http.Error(w, "Invalid Credentials", http.StatusUnauthorized)
return
}
w.Write([]byte("Login successfully!"))
} else {
http.Error(w, "User not found", http.StatusUnauthorized)
}
}
var (
templates *template.Template
users map[string]string
store *sessions.CookieStore
upgrader websocket.Upgrader
)
func init() {
templates = getTemplates()
users = make(map[string]string)
store = sessions.NewCookieStore([]byte("super_secret_key"))
upgrader = websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method Not Supported", http.StatusMethodNotAllowed)
return
}
err := r.ParseForm()
if err != nil {
http.Error(w, "Please pass the data as URL form encoded", http.StatusBadRequest)
return
}
// Retrieve username and password from the form
username := r.Form.Get("username")
password := r.Form.Get("password")
confirmedPassword := r.Form.Get("confirmed_password")
_, exists := users[username]
if exists {
// Returns a new session if there is no current session.
http.Error(w, "User already exists", http.StatusUnauthorized)
} else {
session, _ := store.Get(r, "session.id")
if len(username) > 0 && len(password) > 0 && len(confirmedPassword) > 0 {
if confirmedPassword == password {
users[username] = password
session.Values["authenticated"] = true
session.Save(r, w)
} else {
http.Error(w, "Passwords don't match", http.StatusUnauthorized)
return
}
w.Write([]byte("User has been registered successfully!"))
} else {
http.Error(w, "Please fill in required information", http.StatusUnauthorized)
}
}
}
func main() {
options := domain.GetCliOptions()
hub := domain.MakeHub()
go hub.Run()
setupRoutes(hub, options)
fmt.Printf("Starting server at port %d, with root '%s'\n", options.Port, options.Root)
portStr := fmt.Sprintf(":%d", options.Port)
if err := http.ListenAndServe(portStr, nil); err != nil {
log.Fatal(err)
}
}