Refactor endpoint authentication flow.

Instead of one MatrixAuthenticate() function, we'll do
MatrixGetAccessToken(), and then UserAuthenticate(). This allows us to
give different error messages depending on what the user provided and what
the server state is.
This commit is contained in:
Jordan Bancino 2023-01-17 01:36:22 +00:00
parent 1e02971a7e
commit b0b2f11158
5 changed files with 53 additions and 7 deletions

View file

@ -21,6 +21,7 @@ Milestone: v0.2.0
[x] Username validation [x] Username validation
[x] Password hashing [x] Password hashing
[x] User API [x] User API
[x] Password login
[x] Document MemoryHexDump() [x] Document MemoryHexDump()
[x] Document DbExists() [x] Document DbExists()

View file

@ -302,14 +302,11 @@ MatrixErrorCreate(MatrixError errorArg)
} }
HashMap * HashMap *
MatrixAuthenticate(HttpServerContext * context, Db * db) MatrixGetAccessToken(HttpServerContext * context, char **accessToken)
{ {
HashMap *params; HashMap *params;
char *token; char *token;
(void) db; /* Silence warning about unused var;
* we'll use it eventually. */
params = HttpRequestHeaders(context); params = HttpRequestHeaders(context);
token = HashMapGet(params, "authorization"); token = HashMapGet(params, "authorization");
@ -345,8 +342,7 @@ MatrixAuthenticate(HttpServerContext * context, Db * db)
} }
} }
/* TODO: Check that "token" is actually valid */ *accessToken = token;
return NULL; return NULL;
} }

View file

@ -118,6 +118,52 @@ UserLock(Db * db, char *name)
return user; return user;
} }
User *
UserAuthenticate(Db * db, char *accessToken)
{
User *user;
DbRef *atRef;
char *userName;
char *deviceId;
long expires;
if (!db || !accessToken)
{
return NULL;
}
atRef = DbLock(db, 3, "tokens", "access", accessToken);
if (!atRef)
{
return NULL;
}
userName = JsonValueAsString(HashMapGet(DbJson(atRef), "user"));
deviceId = JsonValueAsString(HashMapGet(DbJson(atRef), "device"));
expires = JsonValueAsInteger(HashMapGet(DbJson(atRef), "expires"));
user = UserLock(db, userName);
if (!user)
{
DbUnlock(db, atRef);
return NULL;
}
if (UtilServerTs() >= (unsigned long) expires)
{
UserUnlock(user);
DbUnlock(db, atRef);
return NULL;
}
/* TODO: Attach deviceId to User */
(void) deviceId;
DbUnlock(db, atRef);
return user;
}
int int
UserUnlock(User * user) UserUnlock(User * user)
{ {

View file

@ -81,7 +81,7 @@ extern HashMap *
MatrixErrorCreate(MatrixError); MatrixErrorCreate(MatrixError);
extern HashMap * extern HashMap *
MatrixAuthenticate(HttpServerContext *, Db *); MatrixGetAccessToken(HttpServerContext *, char **);
extern HashMap * extern HashMap *
MatrixRateLimit(HttpServerContext *, Db *); MatrixRateLimit(HttpServerContext *, Db *);

View file

@ -51,6 +51,9 @@ extern User *
extern User * extern User *
UserLock(Db *, char *name); UserLock(Db *, char *name);
extern User *
UserAuthenticate(Db *, char *accessToken);
extern int extern int
UserUnlock(User *); UserUnlock(User *);