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] Password hashing
[x] User API
[x] Password login
[x] Document MemoryHexDump()
[x] Document DbExists()

View file

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

View file

@ -118,6 +118,52 @@ UserLock(Db * db, char *name)
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
UserUnlock(User * user)
{

View file

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

View file

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