1 /* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
2 * BSD-style license. Please see the COPYING file for details.
15 #define MAX_PASSWORD_LENGTH 64
17 int auth_set_password(const char *username, const char *password) {
21 if (!valid_name(username) || !blerg_exists(username))
25 if (n > MAX_PASSWORD_LENGTH)
28 snprintf(filename, 512, "%s/%s/password", DATA_PATH, username);
29 fd = open(filename, O_WRONLY | O_CREAT, 0600);
30 write(fd, password, n);
36 int auth_get_password(const char *username, char *password) {
41 if (!valid_name(username))
44 sprintf(filename, "%s/%s/password", DATA_PATH, username);
45 fd = open(filename, O_RDONLY);
48 len = read(fd, password, MAX_PASSWORD_LENGTH);
56 int auth_check_password(const char *username, const char *password) {
59 if (auth_get_password(username, epw) == 0)
62 if (strncmp(password, epw, MAX_PASSWORD_LENGTH) == 0)
68 void hexify(char *dst, char *src, int len) {
69 static char hex[] = "0123456789abcdef";
72 for (i = 0; i < len; i++) {
73 dst[i * 2] = hex[(src[i] & 0xF0) >> 4];
74 dst[i * 2 + 1] = hex[src[i] & 0xF];
78 char *create_random_token() {
79 unsigned char buf[TOKEN_SIZE];
83 rand_fd = open("/dev/urandom", O_RDONLY);
85 perror("Could not open /dev/urandom\n");
88 read(rand_fd, buf, TOKEN_SIZE);
91 token = malloc(TOKEN_SIZE * 2 + 1);
92 hexify(token, buf, TOKEN_SIZE);
93 token[TOKEN_SIZE * 2] = 0;
98 char * auth_login(const char *username, const char *password) {
102 if (!auth_check_password(username, password))
105 char *token = create_random_token();
107 sprintf(filename, "%s/%s/tokens", DATA_PATH, username);
108 if (access(filename, F_OK) != 0) {
109 if (mkdir(filename, 0700) == -1) {
110 perror("Could not create auth token dir");
115 sprintf(filename, "%s/%s/tokens/%s", DATA_PATH, username, token);
116 token_fd = open(filename, O_WRONLY | O_CREAT, 0600);
117 if (token_fd == -1) {
118 perror("Could not open token");
126 int auth_logout(const char *username, const char *token) {
129 if (!valid_name(username))
132 sprintf(filename, "%s/%s/tokens", DATA_PATH, username);
133 if (access(filename, F_OK) != 0) {
137 sprintf(filename, "%s/%s/tokens/%s", DATA_PATH, username, token);
138 if (unlink(filename) == -1)
144 int auth_check_token(const char *username, const char *given_token) {
147 sprintf(filename, "%s/%s/tokens/%s", DATA_PATH, username, given_token);
149 return (access(filename, F_OK) == 0);