This repository has been archived on 2024-03-03. You can view files and clone it, but cannot push or open issues or pull requests.
adlin/token-validator/auth.go

114 lines
2.5 KiB
Go

package main
import (
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/julienschmidt/httprouter"
"git.nemunai.re/lectures/adlin/libadlin"
)
var AuthFunc = checkAuth
func init() {
router.GET("/api/auth", apiAuthHandler(validateAuthToken))
router.POST("/api/auth", apiRawHandler(func(w http.ResponseWriter, ps httprouter.Params, body []byte) (interface{}, error) {
return AuthFunc(w, ps, body)
}))
router.POST("/api/auth/logout", apiRawHandler(logout))
}
func validateAuthToken(s adlin.Student, _ httprouter.Params, _ []byte) (interface{}, error) {
return s, nil
}
func logout(w http.ResponseWriter, ps httprouter.Params, body []byte) (interface{}, error) {
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: "",
Path: baseURL + "/",
Expires: time.Unix(0, 0),
Secure: true,
HttpOnly: true,
})
return true, nil
}
type loginForm struct {
Username string
Password string
}
func completeAuth(w http.ResponseWriter, username string, session *adlin.Session) (err error) {
var std adlin.Student
if !adlin.StudentExists(username) {
if std, err = adlin.NewStudent(username); err != nil {
return err
}
} else if std, err = adlin.GetStudentByLogin(username); err != nil {
return err
}
if session == nil {
var s adlin.Session
s, err = std.NewSession()
session = &s
} else {
_, err = session.SetStudent(std)
}
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: base64.StdEncoding.EncodeToString(session.Id),
Path: baseURL + "/",
Expires: time.Now().Add(30 * 24 * time.Hour),
Secure: true,
HttpOnly: true,
})
return nil
}
func dummyAuth(w http.ResponseWriter, _ httprouter.Params, body []byte) (interface{}, error) {
var lf loginForm
if err := json.Unmarshal(body, &lf); err != nil {
return nil, err
}
return map[string]string{"status": "OK"}, completeAuth(w, lf.Username, nil)
}
func checkAuth(w http.ResponseWriter, _ httprouter.Params, body []byte) (interface{}, error) {
var lf loginForm
if err := json.Unmarshal(body, &lf); err != nil {
return nil, err
}
if r, err := http.NewRequest("GET", "https://owncloud.srs.epita.fr/remote.php/dav/", nil); err != nil {
return nil, err
} else {
r.SetBasicAuth(lf.Username, lf.Password)
if resp, err := http.DefaultClient.Do(r); err != nil {
return nil, err
} else {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return dummyAuth(w, nil, body)
} else {
return nil, errors.New(`{"status": "Invalid username or password"}`)
}
}
}
}