fb73e2f4c4eecaaee59e88b8a1205dad2aff37ba
[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                 "tokena 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                 "is 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         osrfLogDebug(OSRF_LOG_MARK,  "oilsAuth retrieved seed from cache: %s", seed );
181         char* maskedPw = md5sum( "%s%s", seed, realPassword );
182         if(!maskedPw) return -1;
183         osrfLogDebug(OSRF_LOG_MARK,  "oilsAuth generated masked password %s. "
184                         "Testing against provided password %s", maskedPw, password );
185
186         if( !strcmp( maskedPw, password ) ) ret = 1;
187
188         free(realPassword);
189         free(seed);
190         free(maskedPw);
191
192         return ret;
193 }
194
195 /**
196  * Calculates the login timeout
197  * 1. If orgloc is 1 or greater and has a timeout specified as an 
198  * org unit setting, it is used
199  * 2. If orgloc is not valid, we check the org unit auth timeout 
200  * setting for the home org unit of the user logging in
201  * 3. If that setting is not defined, we use the configured defaults
202  */
203 double oilsAuthGetTimeout( jsonObject* userObj, char* type, double orgloc ) {
204
205         if(!__oilsAuthOPACTimeout) { /* Load the default timeouts */
206
207                 __oilsAuthOPACTimeout = 
208                         jsonObjectGetNumber( 
209                                 osrf_settings_host_value_object( 
210                                         "/apps/open-ils.auth/app_settings/default_timeout/opac"));
211
212                 __oilsAuthStaffTimeout = 
213                         jsonObjectGetNumber( 
214                                 osrf_settings_host_value_object( 
215                                         "/apps/open-ils.auth/app_settings/default_timeout/staff" ));
216
217                 __oilsAuthOverrideTimeout = 
218                         jsonObjectGetNumber( 
219                                 osrf_settings_host_value_object( 
220                                         "/apps/open-ils.auth/app_settings/default_timeout/temp" ));
221
222
223                 osrfLogInfo(OSRF_LOG_MARK, "Set default auth timetouts: opac => %d : staff => %d : temp => %d",
224                                 __oilsAuthOPACTimeout, __oilsAuthStaffTimeout, __oilsAuthOverrideTimeout );
225         }
226
227         char* setting = NULL;
228
229         double home_ou = jsonObjectGetNumber( oilsFMGetObject( userObj, "home_ou" ) );
230         if(orgloc < 1) orgloc = (int) home_ou;
231
232         if(!strcmp(type, OILS_AUTH_OPAC)) 
233                 setting = OILS_ORG_SETTING_OPAC_TIMEOUT;
234         else if(!strcmp(type, OILS_AUTH_STAFF)) 
235                 setting = OILS_ORG_SETTING_STAFF_TIMEOUT;
236         else if(!strcmp(type, OILS_AUTH_TEMP)) 
237                 setting = OILS_ORG_SETTING_TEMP_TIMEOUT;
238
239         char* timeout = oilsUtilsFetchOrgSetting( orgloc, setting );
240
241         if(!timeout) {
242                 if( orgloc != home_ou ) {
243                         osrfLogDebug(OSRF_LOG_MARK, "Auth timeout not defined for org %d, "
244                                                                 "trying home_ou %d", orgloc, home_ou );
245                         timeout = oilsUtilsFetchOrgSetting( (int) home_ou, setting );
246                 }
247                 if(!timeout) {
248                         if(!strcmp(type, OILS_AUTH_STAFF)) return __oilsAuthStaffTimeout;
249                         if(!strcmp(type, OILS_AUTH_TEMP)) return __oilsAuthOverrideTimeout;
250                         return __oilsAuthOPACTimeout;
251                 }
252         }
253
254         double t = atof(timeout);
255         free(timeout);
256         return t ;
257 }
258
259 /* Adds the authentication token to the user cache.  The timeout for the 
260  * auth token is based on the type of login as well as (if type=='opac') 
261  * the org location id.
262  * Returns the event that should be returned to the user.  
263  * Event must be freed
264  */
265 oilsEvent* oilsAuthHandleLoginOK( 
266                 jsonObject* userObj, char* uname, char* type, double orgloc, char* workstation ) { 
267                 
268         oilsEvent* response;
269
270         double timeout;
271         char* wsorg = jsonObjectToSimpleString(oilsFMGetObject(userObj, "ws_ou"));
272         if(wsorg) { /* if there is a workstation, use it for the timeout */
273                 osrfLogDebug( OSRF_LOG_MARK, 
274                                 "Auth session trying workstation id %d for auth timeout", atoi(wsorg));
275                 timeout = oilsAuthGetTimeout( userObj, type, atoi(wsorg) );
276                 free(wsorg);
277         } else {
278                 osrfLogDebug( OSRF_LOG_MARK, 
279                                 "Auth session trying org from param [%d] for auth timeout", orgloc );
280                 timeout = oilsAuthGetTimeout( userObj, type, orgloc );
281         }
282         osrfLogDebug(OSRF_LOG_MARK, "Auth session timeout for %s: %f", uname, timeout );
283
284         char* string = va_list_to_string( 
285                         "%d.%ld.%s", (long) getpid(), time(NULL), uname ); 
286         char* authToken = md5sum(string); 
287         char* authKey = va_list_to_string( 
288                         "%s%s", OILS_AUTH_CACHE_PRFX, authToken ); 
289
290         char* ws = (workstation) ? workstation : "";
291         osrfLogActivity(OSRF_LOG_MARK,  
292                 "successful login: username=%s, authtoken=%s, workstation=%s", uname, authToken, ws );
293
294         oilsFMSetString( userObj, "passwd", "" );
295         jsonObject* cacheObj = jsonParseStringFmt("{\"authtime\": %f}", timeout);
296         jsonObjectSetKey( cacheObj, "userobj", jsonObjectClone(userObj));
297
298         osrfCachePutObject( authKey, cacheObj, timeout ); 
299         jsonObjectFree(cacheObj);
300         osrfLogInternal(OSRF_LOG_MARK, "oilsAuthComplete(): Placed user object into cache");
301         jsonObject* payload = jsonParseStringFmt(
302                 "{ \"authtoken\": \"%s\", \"authtime\": %f }", authToken, timeout );
303
304         response = oilsNewEvent2( OSRF_LOG_MARK, OILS_EVENT_SUCCESS, payload );
305         free(string); free(authToken); free(authKey);
306         jsonObjectFree(payload);
307
308         return response;
309 }
310
311 oilsEvent* oilsAuthVerifyWorkstation( 
312                 osrfMethodContext* ctx, jsonObject* userObj, char* ws ) {
313         osrfLogInfo(OSRF_LOG_MARK, "Attaching workstation to user at login: %s", ws);
314         jsonObject* workstation = oilsUtilsFetchWorkstationByName(ws);
315         if(!workstation) return oilsNewEvent(OSRF_LOG_MARK, "WORKSTATION_NOT_FOUND");
316         long wsid = oilsFMGetObjectId(workstation);
317         LONG_TO_STRING(wsid);
318         char* orgid = oilsFMGetString(workstation, "owning_lib");
319         oilsFMSetString(userObj, "wsid", LONGSTR);
320         oilsFMSetString(userObj, "ws_ou", orgid);
321         free(orgid);
322         return NULL;
323 }
324
325
326
327 /* see if the card used to login is marked as barred */
328 static oilsEvent* oilsAuthCheckCard( osrfMethodContext* ctx, jsonObject* userObj, char* barcode) {
329         if(!(ctx && userObj && barcode)) return NULL;
330         osrfLogDebug(OSRF_LOG_MARK, "Checking to see if barcode %s is active", barcode);
331
332         jsonObject* params = jsonParseStringFmt("{\"barcode\":\"%s\"}", barcode);
333         jsonObject* card = oilsUtilsQuickReq(
334                 "open-ils.cstore", "open-ils.cstore.direct.actor.card.search", params );
335
336         char* active = oilsFMGetString(card, "active");
337         if( ! oilsUtilsIsDBTrue(active) ) {
338                 free(active);
339                 osrfLogInfo(OSRF_LOG_MARK, "barcode %s is not active, returning event", barcode);
340                 return oilsNewEvent(OSRF_LOG_MARK, "PATRON_CARD_INACTIVE");
341         }
342
343         free(active);
344         return NULL;
345 }
346
347
348
349 int oilsAuthComplete( osrfMethodContext* ctx ) {
350         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
351
352         jsonObject* args                = jsonObjectGetIndex(ctx->params, 0);
353
354         char* uname                             = jsonObjectGetString(jsonObjectGetKey(args, "username"));
355         char* password                  = jsonObjectGetString(jsonObjectGetKey(args, "password"));
356         char* type                              = jsonObjectGetString(jsonObjectGetKey(args, "type"));
357         double orgloc                   = jsonObjectGetNumber(jsonObjectGetKey(args, "org"));
358         char* workstation               = jsonObjectGetString(jsonObjectGetKey(args, "workstation"));
359         char* barcode                   = jsonObjectToSimpleString(jsonObjectGetKey(args, "barcode"));
360
361         char* ws = (workstation) ? workstation : "";
362
363
364         if(!type) type = OILS_AUTH_STAFF;
365
366         if( !( (uname || barcode) && password) ) {
367                 free(barcode);
368                 return osrfAppRequestRespondException( ctx->session, ctx->request, 
369                         "username/barocode and password required for method: %s", ctx->method->name );
370         }
371
372         oilsEvent* response = NULL;
373         jsonObject* userObj = NULL;
374
375         if(uname) userObj = oilsUtilsFetchUserByUsername( uname ); 
376         else if(barcode) userObj = oilsUtilsFetchUserByBarcode( barcode );
377         
378         if(!userObj) { 
379                 response = oilsNewEvent( OSRF_LOG_MARK, OILS_EVENT_AUTH_FAILED );
380                 osrfLogInfo(OSRF_LOG_MARK,  "failed login: username=%s, barcode=%s, workstation=%s", uname, barcode, ws );
381                 osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
382                 oilsEventFree(response);
383                 free(barcode);
384                 return 0;
385         }
386
387         /* first let's see if they have the right credentials */
388         int passOK = -1;
389         if(uname) passOK = oilsAuthVerifyPassword( ctx, userObj, uname, password );
390         else if (barcode) 
391                 passOK = oilsAuthVerifyPassword( ctx, userObj, barcode, password );
392
393         if( passOK < 0 ) {
394                 free(barcode);
395                 return passOK;
396         }
397
398         /* first see if their account is inactive */
399         char* active = oilsFMGetString(userObj, "active");
400         if( !oilsUtilsIsDBTrue(active) ) {
401                 response = oilsNewEvent(OSRF_LOG_MARK, "PATRON_INACTIVE");
402                 osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
403                 oilsEventFree(response);
404                 free(barcode);
405                 free(active);
406                 return 0;
407         }
408         free(active);
409
410         /* then see if the barcode they used is active */
411         if( barcode && (response = oilsAuthCheckCard( ctx, userObj, barcode )) ) {
412                 osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
413                 oilsEventFree(response);
414                 free(barcode);
415                 return 0;
416         }
417
418
419         /* check to see if the user is even allowed to login */
420         if( oilsAuthCheckLoginPerm( ctx, userObj, type ) == -1 ) {
421                 jsonObjectFree(userObj);
422                 free(barcode);
423                 return 0;
424         }
425         
426
427         /* if a workstation is defined, flesh the user with the workstation info */
428         if( workstation != NULL ) {
429                 osrfLogDebug(OSRF_LOG_MARK, "Workstation is %s", workstation);
430                 response = oilsAuthVerifyWorkstation( ctx, userObj, workstation );
431                 if(response) {
432                         jsonObjectFree(userObj);
433                         osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
434                         oilsEventFree(response);
435                         free(barcode);
436                         return 0;
437                 }
438
439         } else {
440                 /* otherwise, use the home org as the workstation org on the user */
441                 char* orgid = oilsFMGetString(userObj, "home_ou");
442                 oilsFMSetString(userObj, "ws_ou", orgid);
443                 free(orgid);
444         }
445
446         int freeuname = 0;
447         if(!uname) {
448                 uname = oilsFMGetString( userObj, "usrname" ); 
449                 freeuname = 1;
450         }
451
452         if( passOK ) {
453                 response = oilsAuthHandleLoginOK( userObj, uname, type, orgloc, workstation );
454
455         } else {
456                 response = oilsNewEvent( OSRF_LOG_MARK, OILS_EVENT_AUTH_FAILED );
457                 osrfLogInfo(OSRF_LOG_MARK,  "failed login: username=%s, barcode=%s, workstation=%s", uname, barcode, ws );
458         }
459
460         jsonObjectFree(userObj);
461         osrfAppRespondComplete( ctx, oilsEventToJSON(response) ); 
462         oilsEventFree(response);
463         free(barcode);
464
465         if(freeuname) free(uname);
466
467         return 0;
468 }
469
470
471
472 int oilsAuthSessionDelete( osrfMethodContext* ctx ) {
473         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
474
475         char* authToken = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0) );
476         jsonObject* resp = NULL;
477
478         if( authToken ) {
479                 osrfLogDebug(OSRF_LOG_MARK, "Removing auth session: %s", authToken );
480                 char* key = va_list_to_string("%s%s", OILS_AUTH_CACHE_PRFX, authToken ); /**/
481                 osrfCacheRemove(key);
482                 resp = jsonNewObject(authToken); /**/
483                 free(key);
484         }
485
486         osrfAppRespondComplete( ctx, resp );
487         jsonObjectFree(resp);
488         return 0;
489 }
490
491 /** Resets the auth login timeout
492  * @return The event object, OILS_EVENT_SUCCESS, or OILS_EVENT_NO_SESSION
493  */
494 oilsEvent*  _oilsAuthResetTimeout( char* authToken ) {
495         if(!authToken) return NULL;
496
497         oilsEvent* evt = NULL;
498         double timeout;
499
500         osrfLogDebug(OSRF_LOG_MARK, "Resetting auth timeout for session %s", authToken);
501         char* key = va_list_to_string("%s%s", OILS_AUTH_CACHE_PRFX, authToken ); 
502         jsonObject* cacheObj = osrfCacheGetObject( key ); 
503
504         if(!cacheObj) {
505                 osrfLogInfo(OSRF_LOG_MARK, "No user in the cache exists with key %s", key);
506                 evt = oilsNewEvent(OSRF_LOG_MARK, OILS_EVENT_NO_SESSION);
507
508         } else {
509
510                 timeout = jsonObjectGetNumber( jsonObjectGetKey( cacheObj, "authtime"));
511                 osrfCacheSetExpire( timeout, key );
512                 jsonObject* payload = jsonNewNumberObject(timeout);
513                 evt = oilsNewEvent2(OSRF_LOG_MARK, OILS_EVENT_SUCCESS, payload);
514                 jsonObjectFree(payload);
515                 jsonObjectFree(cacheObj);
516         }
517
518         free(key);
519         return evt;
520 }
521
522 int oilsAuthResetTimeout( osrfMethodContext* ctx ) {
523         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
524         char* authToken = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0));
525         oilsEvent* evt = _oilsAuthResetTimeout(authToken);
526         osrfAppRespondComplete( ctx, oilsEventToJSON(evt) );
527         oilsEventFree(evt);
528         return 0;
529 }
530
531
532 int oilsAuthSessionRetrieve( osrfMethodContext* ctx ) {
533         OSRF_METHOD_VERIFY_CONTEXT(ctx); 
534
535         char* authToken = jsonObjectGetString( jsonObjectGetIndex(ctx->params, 0));
536         jsonObject* cacheObj = NULL;
537         oilsEvent* evt = NULL;
538
539         if( authToken ){
540
541                 evt = _oilsAuthResetTimeout(authToken);
542
543                 if( evt && strcmp(evt->event, OILS_EVENT_SUCCESS) ) {
544                         osrfAppRespondComplete( ctx, oilsEventToJSON(evt) );
545                         oilsEventFree(evt);
546
547                 } else {
548
549                         osrfLogDebug(OSRF_LOG_MARK, "Retrieving auth session: %s", authToken);
550                         char* key = va_list_to_string("%s%s", OILS_AUTH_CACHE_PRFX, authToken ); 
551                         cacheObj = osrfCacheGetObject( key ); 
552                         if(cacheObj) {
553                                 osrfAppRespondComplete( ctx, jsonObjectGetKey( cacheObj, "userobj"));
554                                 jsonObjectFree(cacheObj);
555                         } else {
556                                 oilsEvent* evt = oilsNewEvent(OSRF_LOG_MARK, OILS_EVENT_NO_SESSION);
557                                 osrfAppRespondComplete( ctx, oilsEventToJSON(evt) ); /* should be event.. */
558                                 oilsEventFree(evt);
559                         }
560                         free(key);
561                 }
562
563         } else {
564
565                 evt = oilsNewEvent(OSRF_LOG_MARK, OILS_EVENT_NO_SESSION);
566                 osrfAppRespondComplete( ctx, oilsEventToJSON(evt) );
567                 oilsEventFree(evt);
568         }
569
570         return 0;
571 }
572
573
574