perf(web): improve authentication

This commit is contained in:
Masahiko AMANO 2023-01-28 19:18:11 +03:00
parent 0a76f7fd8e
commit 607cd6df09
6 changed files with 26 additions and 67 deletions

View File

@ -26,7 +26,6 @@
<link rel="stylesheet" href="/css/auth.css"> <link rel="stylesheet" href="/css/auth.css">
<script src="/js/jquery-3.6.0.min.js"></script> <script src="/js/jquery-3.6.0.min.js"></script>
<script src="/js/jquery.cookie.js"></script> <script src="/js/jquery.cookie.js"></script>
<script src="/js/token.js"></script>
</head> </head>
<body> <body>
<header> <header>

View File

@ -24,9 +24,6 @@
<link rel="stylesheet" href="/css/bootstrap.min.css"> <link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/general.css"> <link rel="stylesheet" href="/css/general.css">
<script src="/js/jquery-3.6.0.min.js"></script> <script src="/js/jquery-3.6.0.min.js"></script>
<script src="/js/jquery.cookie.js"></script>
<script src="/js/token.js"></script>
<script src="/js/redirector.js"></script>
</head> </head>
<body> <body>
<h1>Welcome to Tanabata!</h1> <h1>Welcome to Tanabata!</h1>

View File

@ -1,5 +1,3 @@
$(window).on("load", validate(() => $(".btn-secondary").css("display", "block"), () => {}));
$("#auth").on("submit", function submit(e) { $("#auth").on("submit", function submit(e) {
e.preventDefault(); e.preventDefault();
var input_password = $("#password"); var input_password = $("#password");

View File

@ -1 +0,0 @@
$(window).on("load", validate(() => {}, () => $(location).attr("href", "/auth")));

View File

@ -1,24 +0,0 @@
function validate(onsuccess, onfailure) {
let authorized = true;
if ($.cookie("token") == null) {
authorized = false;
} else {
$.ajax({
url: "/token",
type: "POST",
contentType: "application/json",
data: `{"token":"${$.cookie("token")}"}`,
dataType: "json",
success: function (resp) {
authorized = resp.status;
},
failure: function (err) {
alert(err);
}
});
}
if (authorized) {
return onsuccess;
}
return onfailure;
}

View File

@ -38,11 +38,22 @@ func TokenGenerate(seed []byte) {
TOKEN = fmt.Sprintf("%x", sha256.Sum256([]byte(strconv.FormatInt(value, 16)))) TOKEN = fmt.Sprintf("%x", sha256.Sum256([]byte(strconv.FormatInt(value, 16))))
} }
func TokenValidate(token string) bool { func Auth(handler http.HandlerFunc) http.HandlerFunc {
if time.Now().Unix()-SID >= TOKEN_VALIDTIME || token != TOKEN { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
return false authorized := false
} defer func() {
return true if authorized {
handler.ServeHTTP(w, r)
} else {
http.Redirect(w, r, "/auth", http.StatusSeeOther)
}
}()
token, err := r.Cookie("token")
if err == nil && time.Now().Unix()-SID < TOKEN_VALIDTIME && token.Value == TOKEN {
authorized = true
return
}
})
} }
func HandlerAuth(w http.ResponseWriter, r *http.Request) { func HandlerAuth(w http.ResponseWriter, r *http.Request) {
@ -84,6 +95,11 @@ func HandlerAuth(w http.ResponseWriter, r *http.Request) {
response.Status = true response.Status = true
response.Token = TOKEN response.Token = TOKEN
} }
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: TOKEN,
Expires: time.Now().Add(TOKEN_VALIDTIME * time.Second),
})
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
jsonData, err := json.Marshal(response) jsonData, err := json.Marshal(response)
if err != nil { if err != nil {
@ -95,29 +111,6 @@ func HandlerAuth(w http.ResponseWriter, r *http.Request) {
} }
} }
func HandlerToken(w http.ResponseWriter, r *http.Request) {
var request JSON
var response = JSON{Status: false}
var err error
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
json_decoder := json.NewDecoder(r.Body)
json_decoder.DisallowUnknownFields()
err = json_decoder.Decode(&request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if TokenValidate(request.Token) {
response.Status = true
}
jsonData, err := json.Marshal(response)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, err = w.Write(jsonData)
if err != nil {
log.Println(err)
}
}
func HandlerTDBMS(w http.ResponseWriter, r *http.Request) { func HandlerTDBMS(w http.ResponseWriter, r *http.Request) {
var request JSON var request JSON
var response []byte var response []byte
@ -130,10 +123,6 @@ func HandlerTDBMS(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
if !TokenValidate(request.Token) {
http.Error(w, "Invalid token", http.StatusBadRequest)
return
}
response = tdbms.Query(request.TRDB, request.TRC, request.TRB) response = tdbms.Query(request.TRDB, request.TRC, request.TRB)
if response == nil { if response == nil {
http.Error(w, "Failed to execute request", http.StatusInternalServerError) http.Error(w, "Failed to execute request", http.StatusInternalServerError)
@ -171,10 +160,11 @@ func main() {
public_fs.ServeHTTP(w, r) public_fs.ServeHTTP(w, r)
}) })
http.HandleFunc("/AUTH", HandlerAuth) http.HandleFunc("/AUTH", HandlerAuth)
http.HandleFunc("/token", HandlerToken) http.HandleFunc("/TDBMS", Auth(HandlerTDBMS))
http.HandleFunc("/TDBMS", HandlerTDBMS) tfm_fs := http.StripPrefix("/files", http.FileServer(http.Dir("/srv/data/tfm")))
tfm_fs := http.FileServer(http.Dir("/srv/data/tfm")) http.Handle("/files/", Auth(func(w http.ResponseWriter, r *http.Request) {
http.Handle("/tfm/", http.StripPrefix("/tfm", tfm_fs)) tfm_fs.ServeHTTP(w, r)
}))
log.Println("Running...") log.Println("Running...")
err = server.ListenAndServeTLS("/etc/ssl/certs/web-global.crt", "/etc/ssl/private/web-global.key") err = server.ListenAndServeTLS("/etc/ssl/certs/web-global.crt", "/etc/ssl/private/web-global.key")
if errors.Is(err, http.ErrServerClosed) { if errors.Is(err, http.ErrServerClosed) {