Skip to content
Snippets Groups Projects
Commit d26aae68 authored by Nicolas PAGNY's avatar Nicolas PAGNY
Browse files

Cleaning : deleting unused module + littles corrections

parent 6954d076
No related branches found
No related tags found
No related merge requests found
package adminserver
import (
"net/http"
"os"
"testing"
"forge.grandlyon.com/npernoud/glcpro/pkg/tester"
)
var (
noH map[string]string
)
//TODO : do tests
func TestUserServer(t *testing.T) {
h := CreateAdminServer()
do := tester.CreateHandlerTester(t, h)
do("GET", "/clients", noH, "", http.StatusOK, "")
// Remove the database
os.Remove("./glcpro.db")
}
package apiclient
//TODO : do tests
package apiuser
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"forge.grandlyon.com/npernoud/glcpro/internal/client"
"forge.grandlyon.com/npernoud/glcpro/pkg/common"
"forge.grandlyon.com/npernoud/glcpro/pkg/tokens"
)
// User represents a logged client
type User struct {
ID int `json:"id,omitempty"`
Login string `json:"login"`
}
// TokenData represents the data held into a token
type TokenData struct {
User
URL string `json:"url,omitempty"`
XSRFToken string `json:"xsrftoken,omitempty"`
}
type LoginInfo struct {
Id_user string `json:"id_user,omitempty"`
Secret string `json:"secret,omitempty"`
}
var (
TokenLifeTime time.Duration = 10000
)
type key int
const (
AuthTokenKey = "auth_token"
ContextData key = 0
)
func Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var loginInfos LoginInfo
err := json.NewDecoder(r.Body).Decode(&loginInfos)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, err := client.GetClient(loginInfos.Id_user, loginInfos.Secret)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
xsrfToken, err := common.GenerateRandomString(16)
if err != nil {
http.Error(w, "error generating XSRF Token", http.StatusInternalServerError)
}
tokenData := TokenData{User: User{ID: user.ID, Login: user.Id_client}, XSRFToken: xsrfToken}
tokens.CreateCookie(tokenData, common.GetDomain(r), AuthTokenKey, TokenLifeTime*time.Second, w)
}
func WhoAmI() http.Handler {
whoAmI := func(w http.ResponseWriter, r *http.Request) {
user, err := getTokenData(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(user)
}
return http.HandlerFunc(whoAmI)
}
func getTokenData(r *http.Request) (TokenData, error) {
user, ok := r.Context().Value(ContextData).(TokenData)
if !ok {
return user, errors.New("user could not be got from context")
}
return user, nil
}
func MiddlewareValidateAuth(next http.Handler, checkXSRF bool) http.Handler {
userChecker := func(w http.ResponseWriter, r *http.Request) {
user := TokenData{}
checkXSRF, err := tokens.ExtractAndValidateToken(r, AuthTokenKey, &user, checkXSRF)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if checkXSRF && r.Header.Get("XSRF-TOKEN") != user.XSRFToken {
http.Error(w, "XSRF protection triggered", http.StatusUnauthorized)
}
if user.URL != "" {
requestURL := strings.Split(r.Host, ":")[0] + r.URL.EscapedPath()
if user.URL != requestURL {
http.Error(w, "token restricted to url: "+user.URL, http.StatusUnauthorized)
return
}
}
ctx := context.WithValue(r.Context(), ContextData, user)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(userChecker)
}
......@@ -7,7 +7,7 @@ import (
func TestExists(t *testing.T) {
Init()
db.Exec("DELETE FROM clients")
Create("ID_CLIENT", "SECRET")
Create("ID_CLIENT", "SECRET", "http://localhost:8081")
type args struct {
id_client string
......@@ -37,8 +37,8 @@ func TestUpdate(t *testing.T) {
Init()
db.Exec("DELETE FROM clients")
Create("ID_CLIENT", "SECRET")
Update(1, "ID_CLIENT_UPDATED", "SECRET_UPDATED")
Create("ID_CLIENT", "SECRET", "http://localhost:8081")
Update(1, "ID_CLIENT_UPDATED", "SECRET_UPDATED", "http://localhost:8081")
type args struct {
id_client string
......@@ -67,8 +67,8 @@ func TestDelete(t *testing.T) {
Init()
db.Exec("DELETE FROM clients")
Create("ID_CLIENT", "SECRET")
Create("ID_CLIENT_TO_BE_DELETE", "SECRET_TO_BE_DELETED")
Create("ID_CLIENT", "SECRET", "http://localhost:8081")
Create("ID_CLIENT_TO_BE_DELETE", "SECRET_TO_BE_DELETED", "http://localhost:8081")
Delete(2)
type args struct {
......
//Imports
import {HandleError} from "/services/common/errors.js";
import * as Auth from "/components/auth/auth.js";
export async function mount(where) {
const loginComponent = new Login();
await loginComponent.mount(where);
}
class Login {
constructor() {
}
// DOM elements
login_field
password_field
async mount(mountpoint) {
document.getElementById(mountpoint).innerHTML = /* HTML */ `
<div class="columns">
<div class="column">
<div class="card">
<div class="card-content">
<div class="field">
<p class="control">
<input id="login-login" class="input" type="text" placeholder="Login" />
</p>
</div>
<div class="field">
<p class="control">
<input id="login-password" class="input" type="password" placeholder="Password" />
</p>
</div>
<div class="field">
<a id="login-inmemory" class="button">
Login
</a>
</footer>
</div>
</div>
</div>
`;
this.registerModalFields();
}
registerModalFields() {
this.login_field = document.getElementById("login-login");
this.password_field = document.getElementById("login-password");
this.password_field.addEventListener("keyup", (event) => {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
this.doLogin();
}
});
this.login_inmemory = document.getElementById("login-inmemory");
this.login_inmemory.addEventListener("click", () => {
this.doLogin();
});
}
async doLogin() {
try {
const response = await fetch("/api/user/login", {
method: "POST",
body: JSON.stringify({
Id_user: this.login_field.value,
Secret: this.password_field.value,
}),
});
if (response.status !== 200) {
throw new Error(`Login error (status ${response.status})`);
}
await Auth.getUser()
document.location.href = "/auth"
} catch (e) {
HandleError(e);
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment