1 #ifndef PERDITION_AUTH_H
2 #define PERDITION_AUTH_H
3 
4 #include <string.h>
5 #include <stdlib.h>
6 
7 struct auth {
8 	char *authorisation_id; /* Optional user to use the credentials of
9 				 * to access authentication_id's account.
10 				 * E.g. admin accessing a user's account */
11 	char *authentication_id;
12 	char *passwd;
13 
14 	enum {
15 		auth_t_none = 0,
16 		auth_t_passwd,
17 		auth_t_sasl_plain
18 	} type;
19 };
20 
21 #define STRUCT_AUTH(name) \
22 	struct auth (name) = { .type = auth_t_none }
23 
auth_zero(struct auth * auth)24 static inline void auth_zero(struct auth *auth)
25 {
26 	memset(auth, 0, sizeof *auth);
27 }
28 
auth_set_authorisation_id(struct auth * auth,char * id)29 static inline void auth_set_authorisation_id(struct auth *auth, char *id)
30 {
31 	if (auth->authorisation_id)
32 		auth->authorisation_id = id;
33 	else
34 		auth->authentication_id = id;
35 }
36 
auth_get_authorisation_id(const struct auth * auth)37 static inline char *auth_get_authorisation_id(const struct auth *auth)
38 {
39 	if (auth->authorisation_id)
40 		return auth->authorisation_id;
41 	return auth->authentication_id;
42 }
43 
auth_free_data(const struct auth * auth)44 static inline void auth_free_data(const struct auth *auth)
45 {
46 	if (!auth)
47 		return;
48 
49 	switch (auth->type) {
50 	case auth_t_none:
51 		return;
52 	case auth_t_passwd:
53 	case auth_t_sasl_plain:
54 		break;
55 	}
56 
57 	free(auth->authorisation_id);
58 	free(auth->authentication_id);
59 	free(auth->passwd);
60 }
61 
auth_set_pwd(char * name,char * passwd)62 static inline struct auth auth_set_pwd(char *name, char *passwd)
63 {
64 	struct auth a = {
65 		.type = auth_t_passwd,
66 		.authentication_id = name,
67 		.passwd = passwd
68 	};
69 
70 	return a;
71 }
72 
auth_set_sasl_plain(char * authorisation_id,char * authentication_id,char * passwd)73 static inline struct auth auth_set_sasl_plain(char *authorisation_id,
74 					      char *authentication_id,
75 					      char *passwd)
76 {
77 	struct auth a = {
78 		.type = auth_t_sasl_plain,
79 		.authorisation_id = authorisation_id,
80 		.authentication_id = authentication_id,
81 		.passwd = passwd
82 	};
83 
84 	return a;
85 }
86 
87 struct auth_status {
88 	struct auth auth;
89 	enum {
90 		auth_status_ok = 0,
91 		auth_status_invalid = -1, /* e.g. invalid input */
92 		auth_status_error = -2    /* Internal error */
93 	} status;
94 	char *reason;
95 };
96 
97 #define STRUCT_AUTH_STATUS(name) \
98         struct auth_status (name) = { .status = auth_status_error }
99 
100 #endif /* PERDITION_AUTH_H */
101