Fix insignificant typos, add more INTERNAL debugging
[Evergreen.git] / Open-ILS / src / c-apps / oils_auth.c
1 #include "opensrf/osrf_app_session.h"
2 #include "opensrf/osrf_application.h"
3 #include "opensrf/osrf_settings.h"
4 #include "objson/object.h"
5 #include "opensrf/log.h"
6 #include "oils_utils.h"
7 #include "oils_constants.h"
8 #include "oils_event.h"
9
10 #define OILS_AUTH_CACHE_PRFX "oils_auth_"
11
12 #define MODULENAME "open-ils.auth"
13
14 #define OILS_AUTH_OPAC "opac"
15 #define OILS_AUTH_STAFF "staff"
16 #define OILS_AUTH_TEMP "temp"
17
18 int osrfAppInitialize();
19 int osrfAppChildInit();
20
21 int __oilsAuthOPACTimeout = 0;
22 int __oilsAuthStaffTimeout = 0;
23 int __oilsAuthOverrideTimeout = 0;
24
25
26 int osrfAppInitialize() {
27
28         osrfLogInfo(OSRF_LOG_MARK, "Initializing Auth Server...");
29
30     /* load and parse the IDL */
31         if (!oilsInitIDL(NULL)) return 1; /* return non-zero to indicate error */
32
33         osrfAppRegisterMethod( 
34                 MODULENAME, 
35                 "open-ils.auth.authenticate.init", 
36                 "oilsAuthInit", 
37                 "Start the authentication process and returns the intermediate authentication seed"
38                 " PARAMS( username )", 1, 0 );
39
40         osrfAppRegisterMethod( 
41                 MODULENAME, 
42                 "open-ils.auth.authenticate.complete", 
43                 "oilsAuthComplete", 
44                 "Completes the authentication process.  Returns an object like so: "
45                 "{authtoken : <token>, authtime:<time>}, where authtoken is the login "
46                 "token and authtime is the number of seconds the session will be active"
47                 "PARAMS(username, md5sum( seed + password ), type, org_id ) "
48                 "type can be one of 'opac','staff', or 'temp' and it defaults to 'staff' "
49                 "org_id is the location at which the login should be considered "
50                 "active for login timeout purposes"     , 1, 0 );
51
52         osrfAppRegisterMethod( 
53                 MODULENAME, 
54                 "open-ils.auth.session.retrieve", 
55                 "oilsAuthSessionRetrieve", 
56                 "Pass in the auth token and this retrieves the user object.  The auth "
57                 "timeout is reset when this call is made "
58                 "Returns the user object (password blanked) for the given login session "
59                 "PARAMS( authToken )", 1, 0 );
60
61         osrfAppRegisterMethod( 
62                 MODULENAME, 
63                 "open-ils.auth.session.delete", 
64                 "oilsAuthSessionDelete", 
65                 "Destroys the given login session "
66                 "PARAMS( authToken )",  1, 0 );
67
68         osrfAppRegisterMethod(
69                 MODULENAME,
70                 "open-ils.auth.session.reset_timeout",
71                 "oilsAuthResetTimeout",
72                 "Resets the login timeout for the given session "
73                 "Returns an ILS Event with payload = session_timeout of session "
74                 "if found, otherwise returns the NO_SESSION event"
75                 "PARAMS( authToken )", 1, 0 );
76
77         return 0;
78 }
79
80 int osrfAppChildInit() {
81         return 0;
82 }
83
84 int oilsAuthInit( osrfMethodContext* ctx ) {
85         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
86
87         jsonObject* resp;
88
89         char* username = NULL;
90         char* seed              = NULL;
91         char* md5seed   = NULL;
92         char* key               = NULL;
93
94         if( (username = jsonObjectToSimpleString(jsonObjectGetIndex(ctx->params, 0))) ) {
95
96                 if( strchr( username, ' ' ) ) {
97
98                         /* spaces are not allowed */
99                         resp = jsonNewObject("x");       /* 'x' will never be a valid seed */
100                         osrfAppRespondComplete( ctx, resp );
101
102                 } else {
103
104                         seed = va_list_to_string( "%d.%ld.%s", time(NULL), (long) getpid(), username );
105                         key = va_list_to_string( "%s%s", OILS_AUTH_CACHE_PRFX, username );
106         
107                         md5seed = md5sum(seed);
108                         osrfCachePutString( key, md5seed, 30 );
109         
110                         osrfLogDebug( OSRF_LOG_MARK, "oilsAuthInit(): has seed %s and key %s", md5seed, key );
111         
112                         resp = jsonNewObject(md5seed);  
113                         osrfAppRespondComplete( ctx, resp );
114         
115                         free(seed);
116                         free(md5seed);
117                         free(key);
118                         free(username);
119                 }
120
121                 jsonObjectFree(resp);
122                 return 0;
123         }
124
125         return -1;
126 }
127
128 /** Verifies that the user has permission to login with the 
129  * given type.  If the permission fails, an oilsEvent is returned
130  * to the caller.
131  * @return -1 if the permission check failed, 0 if ther permission
132  * is granted
133  */
134 int oilsAuthCheckLoginPerm( 
135                 osrfMethodContext* ctx, jsonObject* userObj, char* type ) {
136
137         if(!(userObj && type)) return -1;
138         oilsEvent* perm = NULL;
139
140         if(!strcasecmp(type, OILS_AUTH_OPAC)) {
141                 char* permissions[] = { "OPAC_LOGIN" };
142                 perm = oilsUtilsCheckPerms( oilsFMGetObjectId( userObj ), -1, permissions, 1 );
143
144         } else if(!strcasecmp(type, OILS_AUTH_STAFF)) {
145                 char* permissions[] = { "STAFF_LOGIN" };
146                 perm = oilsUtilsCheckPerms( oilsFMGetObjectId( userObj ), -1, permissions, 1 );
147
148         } else if(!strcasecmp(type, OILS_AUTH_TEMP)) {
149                 char* permissions[] = { "STAFF_LOGIN" };
150                 perm = oilsUtilsCheckPerms( oilsFMGetObjectId( userObj ), -1, permissions, 1 );
151         }
152
153         if(perm) {
154                 osrfAppRespondComplete( ctx, oilsEventToJSON(perm) ); 
155                 oilsEventFree(perm);
156                 return -1;
157         }
158
159         return 0;
160 }
161
162 /**
163  * Returns 1 if the password provided matches the user's real password
164  * Returns 0 otherwise
165  * Returns -1 on error
166  */
167 int oilsAuthVerifyPassword( 
168                 osrfMethodContext* ctx, jsonObject* userObj, char* uname, char* password ) {
169
170         int ret = 0;
171         char* realPassword = oilsFMGetString( userObj, "passwd" ); /**/
172         char* seed = osrfCacheGetString( "%s%s", OILS_AUTH_CACHE_PRFX, uname ); /**/
173
174         if(!seed) {
175                 return osrfAppRequestRespondException( ctx->session,
176                         ctx->request, "No authentication seed found. "
177                         "open-ils.auth.authenticate.init must be called first");
178         }
179
180         osrfLogInternal(OSRF_LOG_MARK, "oilsAuth retrieved real password: [%s]", realPassword);
181         osrfLogDebug(OSRF_LOG_MARK,  "oilsAuth retrieved seed from cache: %s", seed );
182         char* maskedPw = md5sum( "%s%s", seed, realPassword );
183         if(!maskedPw) return -1;
184         osrfLogDebug(OSRF_LOG_MARK,  "oilsAuth generated masked password %s. "
185                         "Testing against provided password %s", maskedPw, password );
186
187         if( !strcmp( maskedPw, password ) ) ret = 1;
188
189         free(realPassword);
190         free(seed);
191         free(maskedPw);
192
193         return ret;
194 }
195
196 /**
197  * Calculates the login timeout
198  * 1. If orgloc is 1 or greater and has a timeout specified as an 
199  * org unit setting, it is used
200  * 2. If orgloc is not valid, we check the org unit auth timeout 
201  * setting for the home org unit of the user logging in
202  * 3. If that setting is not defined, we use the configured defaults
203  */
204 double oilsAuthGetTimeout( jsonObject* userObj, char* type, double orgloc ) {
205
206         if(!__oilsAuthOPACTimeout) { /* Load the default timeouts */
207
208                 __oilsAuthOPACTimeout = 
209                         jsonObjectGetNumber( 
210                                 osrf_settings_host_value_object( 
211                                         "/apps/open-ils.auth/app_settings/default_timeout/opac"));
212
213                 __oilsAuthStaffTimeout = 
214                         jsonObjectGetNumber( 
215                                 osrf_settings_host_value_object( 
216                                         "/apps/open-ils.auth/app_settings/default_timeout/staff" ));
217
218                 __oilsAuthOverrideTimeout = 
219                         jsonObjectGetNumber( 
220                                 osrf_settings_host_value_object( 
221                                         "/apps/open-ils.auth/app_settings/default_timeout/temp" ));
222
223
224                 osrfLogInfo(OSRF_LOG_MARK, "Set default auth timetouts: opac => %d : staff => %d : temp => %d",
225                                 __oilsAuthOPACTimeout, __oilsAuthStaffTimeout, __oilsAuthOverrideTimeout );
226         }
227
228         char* setting = NULL;
229
230         double home_ou = jsonObjectGetNumber( oilsFMGetObject( userObj, "home_ou" ) );
231         if(orgloc < 1) orgloc = (int) home_ou;
232
233         if(!strcmp(type, OILS_AUTH_OPAC)) 
234                 setting = OILS_ORG_SETTING_OPAC_TIMEOUT;
235         else if(!strcmp(type, OILS_AUTH_STAFF)) 
236                 setting = OILS_ORG_SETTING_STAFF_TIMEOUT;
237         else if(!strcmp(type, OILS_AUTH_TEMP)) 
238                 setting = OILS_ORG_SETTING_TEMP_TIMEOUT;
239
240         char* timeout = oilsUtilsFetchOrgSetting( orgloc, setting );
241
242         if(!timeout) {
243                 if( orgloc != home_ou ) {
244                         osrfLogDebug(OSRF_LOG_MARK, "Auth timeout not defined for org %d, "
245                                                                 "trying home_ou %d", orgloc, home_ou );
246                         timeout = oilsUtilsFetchOrgSetting( (int) home_ou, setting );
247                 }
248                 if(!timeout) {
249                         if(!strcmp(type, OILS_AUTH_STAFF)) return __oilsAuthStaffTimeout;
250                         if(!strcmp(type, OILS_AUTH_TEMP)) return __oilsAuthOverrideTimeout;
251                         return __oilsAuthOPACTimeout;
252                 }
253         }
254
255         double t = atof(timeout);
256         free(timeout);
257         return t ;
258 }
259
260 /* Adds the authentication token to the user cache.  The timeout for the 
261  * auth token is based on the type of login as well as (if type=='opac') 
262  * the org location id.
263  * Returns the event that should be returned to the user.  
264  * Event must be freed
265  */
266 oilsEvent* oilsAuthHandleLoginOK( 
267                 jsonObject* userObj, char* uname, char* type, double orgloc, char* workstation ) { 
268                 
269         oilsEvent* response;
270
271         double timeout;
272         char* wsorg = jsonObjectToSimpleString(oilsFMGetObject(userObj, "ws_ou"));
273         if(wsorg) { /* if there is a workstation, use it for the timeout */
274                 osrfLogDebug( OSRF_LOG_MARK, 
275                                 "Auth session trying workstation id %d for auth timeout", atoi(wsorg));
276                 timeout = oilsAuthGetTimeout( userObj, type, atoi(wsorg) );
277                 free(wsorg);
278         } else {
279                 osrfLogDebug( OSRF_LOG_MARK, 
280                                 "Auth session trying org from param [%d] for auth timeout", orgloc );
281                 timeout = oilsAuthGetTimeout( userObj, type, orgloc );
282         }
283         osrfLogDebug(OSRF_LOG_MARK, "Auth session timeout for %s: %f", uname, timeout );
284
285         char* string = va_list_to_string( 
286                         "%d.%ld.%s", (long) getpid(), time(NULL), uname ); 
287         char* authToken = md5sum(string); 
288         char* authKey = va_list_to_string( 
289                         "%s%s", OILS_AUTH_CACHE_PRFX, authToken ); 
290
291         char* ws = (workstation) ? workstation : "";
292         osrfLogActivity(OSRF_LOG_MARK,  
293                 "successful login: username=%s, authtoken=%s, workstation=%s", uname, authToken, ws );
294
295         oilsFMSetString( userObj, "passwd", "" );
296         jsonObject* cacheObj = jsonParseStringFmt("{\"authtime\": %f}", timeout);
297         jsonObjectSetKey( cacheObj, "userobj", jsonObjectClone(userObj));
298
299         osrfCachePutObject( authKey, cacheObj, timeout ); 
300         jsonObjectFree(cacheObj);
301         osrfLogInternal(OSRF_LOG_MARK, "oilsAuthComplete(): Placed user object into cache");
302         jsonObject* payload = jsonParseStringFmt(
303                 "{ \"authtoken\": \"%s\", \"authtime\": %f }", authToken, timeout );
304
305         response = oilsNewEvent2( OSRF_LOG_MARK, OILS_EVENT_SUCCESS, payload );
306         free(string); free(authToken); free(authKey);
307         jsonObjectFree(payload);
308
309         return response;
310 }
311
312 oilsEvent* oilsAuthVerifyWorkstation( 
313                 osrfMethodContext* ctx, jsonObject* userObj, char* ws ) {
314         osrfLogInfo(OSRF_LOG_MARK, "Attaching workstation to user at login: %s", ws);
315         jsonObject* workstation = oilsUtilsFetchWorkstationByName(ws);
316         if(!workstation) return oilsNewEvent(OSRF_LOG_MARK, "WORKSTATION_NOT_FOUND");
317         long wsid = oilsFMGetObjectId(workstation);
318         LONG_TO_STRING(wsid);
319         char* orgid = oilsFMGetString(workstation, "owning_lib");
320         oilsFMSetString(userObj, "wsid", LONGSTR);
321         oilsFMSetString(userObj, "ws_ou", orgid);
322         free(orgid);
323         return NULL;
324 }
325
326
327
328 /* see if the card used to login is marked as barred */
329 static oilsEvent* oilsAuthCheckCard( osrfMethodContext* ctx, jsonObject* userObj, char* barcode) {
330         if(!(ctx && userObj && barcode)) return NULL;
331         osrfLogDebug(OSRF_LOG_MARK, "Checking to see if barcode %s is active", barcode);
332
333         jsonObject* params = jsonParseStringFmt("{\"barcode\":\"%s\"}", barcode);
334         jsonObject* card = oilsUtilsQuickReq(
335                 "open-ils.cstore", "open-ils.cstore.direct.actor.card.search", params );
336
337         char* active = oilsFMGetString(card, "active");
338         if( ! oilsUtilsIsDBTrue(active) ) {
339                 free(active);
340                 osrfLogInfo(OSRF_LOG_MARK, "barcode %s is not active, returning event", barcode);
341                 return oilsNewEvent(OSRF_LOG_MARK, "PATRON_CARD_INACTIVE");
342         }
343
344         free(active);
345         return NULL;
346 }
347
348
349
350 int oilsAuthComplete( osrfMethodContext* ctx ) {
351         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
352
353         jsonObject* args                = jsonObjectGetIndex(ctx->params, 0);
354
355         char* uname                             = jsonObjectGetString(jsonObjectGetKey(args, "username"));
356         char* password                  = jsonObjectGetString(jsonObjectGetKey(args, "password"));
357         char* type                              = jsonObjectGetString(jsonObjectGetKey(args, "type"));
358         double orgloc                   = jsonObjectGetNumber(jsonObjectGetKey(args, "org"));
359         char* workstation               = jsonObjectGetString(jsonObjectGetKey(args, "workstation"));
360         char* barcode                   = jsonObjectToSimpleString(jsonObjectGetKey(args, "barcode"));
361
362         char* ws = (workstation) ? workstation : "";
363
364
365         if(!type) type = OILS_AUTH_STAFF;
366
367         if( !( (uname || barcode) && password) ) {
368                 free(barcode);
369                 return osrfAppRequestRespondException( ctx->session, ctx->request, 
370                         "username/barcode and password required for method: %s", ctx->method->name );
371         }
372
373         oilsEvent* response = NULL;
374         jsonObject* userObj = NULL;
375
376         if(uname) userObj = oilsUtilsFetchUserByUsername( uname ); 
377         else if(barcode) userObj = oilsUtilsFetchUserByBarcode( barcode );
378         
379         if(!userObj) { 
380                 response = oilsNewEvent( OSRF_LOG_MARK, OILS_EVENT_AUTH_FAILED );
381                 osrfLogInfo(OSRF_LOG_MARK,  "failed login: username=%s, barcode=%s, workstation=%s", uname, barcode, ws );
382                 osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
383                 oilsEventFree(response);
384                 free(barcode);
385                 return 0;
386         }
387
388         /* first let's see if they have the right credentials */
389         int passOK = -1;
390         if(uname) passOK = oilsAuthVerifyPassword( ctx, userObj, uname, password );
391         else if (barcode) 
392                 passOK = oilsAuthVerifyPassword( ctx, userObj, barcode, password );
393
394         if( passOK < 0 ) {
395                 free(barcode);
396                 return passOK;
397         }
398
399         /* first see if their account is inactive */
400         char* active = oilsFMGetString(userObj, "active");
401         if( !oilsUtilsIsDBTrue(active) ) {
402                 response = oilsNewEvent(OSRF_LOG_MARK, "PATRON_INACTIVE");
403                 osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
404                 oilsEventFree(response);
405                 free(barcode);
406                 free(active);
407                 return 0;
408         }
409         free(active);
410
411         /* then see if the barcode they used is active */
412         if( barcode && (response = oilsAuthCheckCard( ctx, userObj, barcode )) ) {
413                 osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
414                 oilsEventFree(response);
415                 free(barcode);
416                 return 0;
417         }
418
419
420         /* check to see if the user is even allowed to login */
421         if( oilsAuthCheckLoginPerm( ctx, userObj, type ) == -1 ) {
422                 jsonObjectFree(userObj);
423                 free(barcode);
424                 return 0;
425         }
426         
427
428         /* if a workstation is defined, flesh the user with the workstation info */
429         if( workstation != NULL ) {
430                 osrfLogDebug(OSRF_LOG_MARK, "Workstation is %s", workstation);
431                 response = oilsAuthVerifyWorkstation( ctx, userObj, workstation );
432                 if(response) {
433                         jsonObjectFree(userObj);
434                         osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
435                         oilsEventFree(response);
436                         free(barcode);
437                         return 0;
438                 }
439
440         } else {
441                 /* otherwise, use the home org as the workstation org on the user */
442                 char* orgid = oilsFMGetString(userObj, "home_ou");
443                 oilsFMSetString(userObj, "ws_ou", orgid);
444                 free(orgid);
445         }
446
447         int freeuname = 0;
448         if(!uname) {
449                 uname = oilsFMGetString( userObj, "usrname" ); 
450                 freeuname = 1;
451         }
452
453         if( passOK ) {
454                 response = oilsAuthHandleLoginOK( userObj, uname, type, orgloc, workstation );
455
456         } else {
457                 response = oilsNewEvent( OSRF_LOG_MARK, OILS_EVENT_AUTH_FAILED );
458                 osrfLogInfo(OSRF_LOG_MARK,  "failed login: username=%s, barcode=%s, workstation=%s", uname, barcode, ws );
459         }
460
461         jsonObjectFree(userObj);
462         osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
463         oilsEventFree(response);
464         free(barcode);
465
466         if(freeuname) free(uname);
467
468         return 0;
469 }
470
471
472
473 int oilsAuthSessionDelete( osrfMethodContext* ctx ) {
474         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
475
476         char* authToken = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0) );
477         jsonObject* resp = NULL;
478
479         if( authToken ) {
480                 osrfLogDebug(OSRF_LOG_MARK, "Removing auth session: %s", authToken );
481                 char* key = va_list_to_string("%s%s", OILS_AUTH_CACHE_PRFX, authToken ); /**/
482                 osrfCacheRemove(key);
483                 resp = jsonNewObject(authToken); /**/
484                 free(key);
485         }
486
487         osrfAppRespondComplete( ctx, resp );
488         jsonObjectFree(resp);
489         return 0;
490 }
491
492 /** Resets the auth login timeout
493  * @return The event object, OILS_EVENT_SUCCESS, or OILS_EVENT_NO_SESSION
494  */
495 oilsEvent*  _oilsAuthResetTimeout( char* authToken ) {
496         if(!authToken) return NULL;
497
498         oilsEvent* evt = NULL;
499         double timeout;
500
501         osrfLogDebug(OSRF_LOG_MARK, "Resetting auth timeout for session %s", authToken);
502         char* key = va_list_to_string("%s%s", OILS_AUTH_CACHE_PRFX, authToken ); 
503         jsonObject* cacheObj = osrfCacheGetObject( key ); 
504
505         if(!cacheObj) {
506                 osrfLogInfo(OSRF_LOG_MARK, "No user in the cache exists with key %s", key);
507                 evt = oilsNewEvent(OSRF_LOG_MARK, OILS_EVENT_NO_SESSION);
508
509         } else {
510
511                 timeout = jsonObjectGetNumber( jsonObjectGetKey( cacheObj, "authtime"));
512                 osrfCacheSetExpire( timeout, key );
513                 jsonObject* payload = jsonNewNumberObject(timeout);
514                 evt = oilsNewEvent2(OSRF_LOG_MARK, OILS_EVENT_SUCCESS, payload);
515                 jsonObjectFree(payload);
516                 jsonObjectFree(cacheObj);
517         }
518
519         free(key);
520         return evt;
521 }
522
523 int oilsAuthResetTimeout( osrfMethodContext* ctx ) {
524         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
525         char* authToken = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0));
526         oilsEvent* evt = _oilsAuthResetTimeout(authToken);
527         osrfAppRespondComplete( ctx, oilsEventToJSON(evt) );
528         oilsEventFree(evt);
529         return 0;
530 }
531
532
533 int oilsAuthSessionRetrieve( osrfMethodContext* ctx ) {
534         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
535
536         char* authToken = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0));
537         jsonObject* cacheObj = NULL;
538         oilsEvent* evt = NULL;
539
540         if( authToken ){
541
542                 evt = _oilsAuthResetTimeout(authToken);
543
544                 if( evt && strcmp(evt->event, OILS_EVENT_SUCCESS) ) {
545                         osrfAppRespondComplete( ctx, oilsEventToJSON(evt) );
546                         oilsEventFree(evt);
547
548                 } else {
549
550                         osrfLogDebug(OSRF_LOG_MARK, "Retrieving auth session: %s", authToken);
551                         char* key = va_list_to_string("%s%s", OILS_AUTH_CACHE_PRFX, authToken ); 
552                         cacheObj = osrfCacheGetObject( key ); 
553                         if(cacheObj) {
554                                 osrfAppRespondComplete( ctx, jsonObjectGetKey( cacheObj, "userobj"));
555                                 jsonObjectFree(cacheObj);
556                         } else {
557                                 oilsEvent* evt = oilsNewEvent(OSRF_LOG_MARK, OILS_EVENT_NO_SESSION);
558                                 osrfAppRespondComplete( ctx, oilsEventToJSON(evt) ); /* should be event.. */
559                                 oilsEventFree(evt);
560                         }
561                         free(key);
562                 }
563
564         } else {
565
566                 evt = oilsNewEvent(OSRF_LOG_MARK, OILS_EVENT_NO_SESSION);
567                 osrfAppRespondComplete( ctx, oilsEventToJSON(evt) );
568                 oilsEventFree(evt);
569         }
570
571         return 0;
572 }
573
574
575