databag/net/server/internal/api_authorize.go

75 lines
1.7 KiB
Go
Raw Normal View History

2022-01-11 06:20:32 +00:00
package databag
import (
"crypto"
"crypto/rand"
"crypto/sha256"
"crypto/rsa"
2022-01-11 06:20:32 +00:00
"net/http"
"encoding/json"
"encoding/base64"
2022-01-18 08:40:39 +00:00
"time"
2022-01-11 06:20:32 +00:00
)
2022-01-13 05:23:18 +00:00
func Authorize(w http.ResponseWriter, r *http.Request) {
account, res := BearerAppToken(r, true);
if res != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
if account.Disabled {
w.WriteHeader(http.StatusGone);
return
}
2022-01-18 08:40:39 +00:00
// extract token from body
var token string
err := ParseRequest(r, w, &token)
if err != nil {
2022-01-19 08:03:46 +00:00
w.WriteHeader(http.StatusBadRequest)
2022-01-18 08:40:39 +00:00
return
}
// load details to sign data
if account.AccountDetail.KeyType != "RSA4096" {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
privateKey, res := ParseRsaPrivateKeyFromPemStr(account.AccountDetail.PrivateKey);
if res != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
2022-01-18 08:40:39 +00:00
// generate message
auth := Authenticate{
Guid: account.Guid,
Token: token,
Timestamp: time.Now().Unix(),
}
var data []byte
data, err = json.Marshal(auth);
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
hash := sha256.Sum256(data);
var signature []byte
signature, err = rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hash[:])
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
msg := DataMessage{
MessageType: "authenticate",
Message: base64.StdEncoding.EncodeToString([]byte(data)),
KeyType: account.AccountDetail.KeyType,
PublicKey: base64.StdEncoding.EncodeToString([]byte(account.AccountDetail.PublicKey)),
Signature: base64.StdEncoding.EncodeToString(signature),
SignatureType: "PKCS1v15",
}
2022-01-18 08:40:39 +00:00
WriteResponse(w, msg)
2022-01-11 06:20:32 +00:00
}