def login(request, tag=None): from uds.web.forms.LoginForm import LoginForm from uds.web.util.authentication import checkLogin from uds.core.auths.auth import webLogin from django.http import HttpResponseRedirect # Default empty form if request.method == 'POST': form = LoginForm(request.POST, tag=tag) user, data = checkLogin(request, form, tag) if user: response = HttpResponseRedirect(reverse('page.index')) webLogin(request, response, user, data) # data is user password here else: # If error is numeric, redirect... # Error, set error on session for process for js if isinstance(data, int): return errorView(request, data) request.session['errors'] = [data] return index(request) else: response = index(request) return response
def login(request: ExtendedHttpRequest, tag: typing.Optional[str] = None) -> HttpResponse: # Default empty form logger.debug('Tag: %s', tag) if request.method == 'POST': request.session['restricted'] = False # Access is from login form = LoginForm(request.POST, tag=tag) user, data = checkLogin(request, form, tag) if user: response = HttpResponseRedirect(reverse('page.index')) # save tag, weblogin will clear session tag = request.session.get('tag') auth.webLogin(request, response, user, data) # data is user password here # And restore tag request.session['tag'] = tag else: # If error is numeric, redirect... # Error, set error on session for process for js time.sleep(2) # On failure, wait a bit... if isinstance(data, int): return errors.errorView(request, data) request.session['errors'] = [data] return index(request) else: request.session['tag'] = tag response = index(request) return response
def authCallback(request, authName): """ This url is provided so external SSO authenticators can get an url for redirecting back the users. This will invoke authCallback of the requested idAuth and, if this represents an authenticator that has an authCallback """ from uds.core import auths try: authenticator = Authenticator.objects.get(name=authName) params = request.GET.copy() params.update(request.POST) logger.debug('Request session:%s -> %s, %s', request.ip, request.session.keys(), request.session.session_key) params['_request'] = request # params['_session'] = request.session # params['_user'] = request.user logger.debug('Auth callback for {0} with params {1}'.format( authenticator, params.keys())) user = authenticateViaCallback(authenticator, params) os = OsDetector.getOsFromUA(request.META['HTTP_USER_AGENT']) if user is None: authLogLogin(request, authenticator, '{0}'.format(params), 'Invalid at auth callback') raise auths.Exceptions.InvalidUserException() response = HttpResponseRedirect(reverse('Index')) webLogin(request, response, user, '') # Password is unavailable in this case request.session['OS'] = os # Now we render an intermediate page, so we get Java support from user # It will only detect java, and them redirect to Java return response except auths.Exceptions.Redirect as e: return HttpResponseRedirect(request.build_absolute_uri(str(e))) except auths.Exceptions.Logout as e: return webLogout(request, request.build_absolute_uri(str(e))) except Exception as e: logger.exception('authCallback') return errors.exceptionView(request, e) # Will never reach this raise RuntimeError('Unreachable point reached!!!')
def authCallback_stage2(request: HttpRequest, ticketId: str) -> HttpResponse: try: ticket = TicketStore.get(ticketId) params: typing.Dict[str, typing.Any] = ticket['params'] auth_uuid: str = ticket['auth'] authenticator = Authenticator.objects.get(uuid=auth_uuid) params['_request'] = request # params['_session'] = request.session # params['_user'] = request.user logger.debug('Request session:%s -> %s, %s', request.ip, request.session.keys(), request.session.session_key) user = authenticateViaCallback(authenticator, params) os = OsDetector.getOsFromUA(request.META['HTTP_USER_AGENT']) if user is None: authLogLogin(request, authenticator, '{0}'.format(params), 'Invalid at auth callback') raise auths.exceptions.InvalidUserException() response = HttpResponseRedirect(reverse('page.index')) webLogin(request, response, user, '') # Password is unavailable in this case request.session['OS'] = os # Now we render an intermediate page, so we get Java support from user # It will only detect java, and them redirect to Java return response except auths.exceptions.Redirect as e: return HttpResponseRedirect( request.build_absolute_uri(str(e)) if e.args and e.args[0] else '/' ) except auths.exceptions.Logout as e: return webLogout( request, request.build_absolute_uri(str(e)) if e.args and e.args[0] else None) except Exception as e: logger.exception('authCallback') return errors.exceptionView(request, e) # Will never reach this raise RuntimeError('Unreachable point reached!!!')
def authCallback(request, authName): """ This url is provided so external SSO authenticators can get an url for redirecting back the users. This will invoke authCallback of the requested idAuth and, if this represents an authenticator that has an authCallback """ from uds.core import auths try: authenticator = Authenticator.objects.get(name=authName) params = request.GET.copy() params.update(request.POST) params['_request'] = request # params['_session'] = request.session # params['_user'] = request.user logger.debug('Auth callback for {0} with params {1}'.format(authenticator, params.keys())) user = authenticateViaCallback(authenticator, params) os = OsDetector.getOsFromUA(request.META['HTTP_USER_AGENT']) if user is None: authLogLogin(request, authenticator, '{0}'.format(params), 'Invalid at auth callback') raise auths.Exceptions.InvalidUserException() response = HttpResponseRedirect(reverse('Index')) webLogin(request, response, user, '') # Password is unavailable in this case request.session['OS'] = os # Now we render an intermediate page, so we get Java support from user # It will only detect java, and them redirect to Java return response except auths.Exceptions.Redirect as e: return HttpResponseRedirect(request.build_absolute_uri(str(e))) except auths.Exceptions.Logout as e: return webLogout(request, request.build_absolute_uri(str(e))) except Exception as e: logger.exception('authCallback') return errors.exceptionView(request, e) # Will never reach this raise RuntimeError('Unreachable point reached!!!')
def login(request: HttpRequest, tag: typing.Optional[str] = None) -> HttpResponse: # Default empty form if request.method == 'POST': form = LoginForm(request.POST, tag=tag) user, data = checkLogin(request, form, tag) if user: response = HttpResponseRedirect(reverse('page.index')) auth.webLogin(request, response, user, data) # data is user password here else: # If error is numeric, redirect... # Error, set error on session for process for js if isinstance(data, int): return errors.errorView(request, data) request.session['errors'] = [data] return index(request) else: request.session['tag'] = tag response = index(request) return response
def login(request, tag=None): """ View responsible of logging in an user :param request: http request :param tag: tag of login auth """ # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt()) response = None # Default empty form form = LoginForm(tag=tag) if request.method == 'POST': form = LoginForm(request.POST, tag=tag) user, data = checkLogin(request, form, tag) if user: response = HttpResponseRedirect(reverse('uds.web.views.index')) webLogin(request, response, user, data) # data is user password here else: # error, data = error if isinstance(data, int): return errors.errorView(request, data) # Error to notify form.add_error(None, data) if response is None: response = render(request, theme.template('login.html'), { 'form': form, 'authenticators': Authenticator.getByTag(tag), 'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True), 'version': VERSION } ) getUDSCookie(request, response) return response
def ticketAuth(request: 'HttpRequest', ticketId: str) -> HttpResponse: # pylint: disable=too-many-locals,too-many-branches,too-many-statements """ Used to authenticate an user via a ticket """ try: data = TicketStore.get(ticketId, invalidate=True) try: # Extract ticket.data from ticket.data storage, and remove it if success username = data['username'] groups = data['groups'] auth = data['auth'] realname = data['realname'] servicePool = data['servicePool'] password = cryptoManager().decrypt(data['password']) transport = data['transport'] except Exception: logger.error('Ticket stored is not valid') raise auths.exceptions.InvalidUserException() auth = Authenticator.objects.get(uuid=auth) # If user does not exists in DB, create it right now # Add user to groups, if they exists... grps: typing.List = [] for g in groups: try: grps.append(auth.groups.get(uuid=g)) except Exception: logger.debug('Group list has changed since ticket assignment') if not grps: logger.error('Ticket has no valid groups') raise Exception('Invalid ticket authentication') usr = auth.getOrCreateUser(username, realname) if usr is None or State.isActive( usr.state) is False: # If user is inactive, raise an exception raise auths.exceptions.InvalidUserException() # Add groups to user (replace existing groups) usr.groups.set(grps) # Force cookie generation webLogin(request, None, usr, password) request.user = usr # Temporarily store this user as "authenticated" user, next requests will be done using session request.session[ 'ticket'] = '1' # Store that user access is done using ticket # Override and recalc transport based on current os transport = None logger.debug("Service & transport: %s, %s", servicePool, transport) # Check if servicePool is part of the ticket if servicePool: # If service pool is in there, also is transport res = userServiceManager().getService(request.user, request.os, request.ip, 'F' + servicePool, transport, False) _, userService, _, transport, _ = res transportInstance = transport.getInstance() if transportInstance.ownLink is True: link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid)) else: link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid) request.session['launch'] = link response = HttpResponseRedirect(reverse('page.ticket.launcher')) else: response = HttpResponseRedirect(reverse('page.index')) # Now ensure uds cookie is at response getUDSCookie(request, response, True) return response except ServiceNotReadyError as e: return errors.errorView(request, errors.SERVICE_NOT_READY) except TicketStore.InvalidTicket: return errors.errorView(request, errors.RELOAD_NOT_SUPPORTED) except Authenticator.DoesNotExist: logger.error('Ticket has an non existing authenticator') return errors.errorView(request, errors.ACCESS_DENIED) except ServicePool.DoesNotExist: logger.error('Ticket has an invalid Service Pool') return errors.errorView(request, errors.SERVICE_NOT_FOUND) except Exception as e: logger.exception('Exception') return errors.exceptionView(request, e)
def login(request, tag=None): ''' View responsible of logging in an user :param request: http request :param tag: tag of login auth ''' # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt()) host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host' # Last one is a placeholder in case we can't locate host name # Get Authenticators limitation logger.debug('Host: {0}'.format(host)) if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(True) is True: if tag is None: try: Authenticator.objects.get(small_name=host) tag = host except Exception: try: tag = Authenticator.objects.order_by('priority')[0].small_name except Exception: # There is no authenticators yet, simply allow global login to nowhere.. :-) tag = None logger.debug('Tag: {0}'.format(tag)) logger.debug(request.method) if request.method == 'POST': if 'uds' not in request.COOKIES: logger.debug('Request does not have uds cookie') return errors.errorView(request, errors.COOKIES_NEEDED) # We need cookies to keep session data request.session.cycle_key() form = LoginForm(request.POST, tag=tag) if form.is_valid(): os = OsDetector.getOsFromUA(request.META.get('HTTP_USER_AGENT')) try: authenticator = Authenticator.objects.get(pk=form.cleaned_data['authenticator']) except Exception: authenticator = Authenticator() userName = form.cleaned_data['user'] cache = Cache('auth') cacheKey = str(authenticator.id) + userName tries = cache.get(cacheKey) if tries is None: tries = 0 if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt(): form.add_form_error('Too many authentication errors. User temporarily blocked.') authLogLogin(request, authenticator, userName, 'Temporarily blocked') else: user = authenticate(userName, form.cleaned_data['password'], authenticator) logger.debug('User: {}'.format(user)) if user is None: logger.debug("Invalid credentials for user {0}".format(userName)) tries += 1 cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt()) form.add_form_error('Invalid credentials') authLogLogin(request, authenticator, userName, 'Invalid credentials') else: logger.debug('User {} has logged in'.format(userName)) cache.remove(cacheKey) # Valid login, remove cached tries response = HttpResponseRedirect(reverse('uds.web.views.index')) webLogin(request, response, user, form.cleaned_data['password']) # Add the "java supported" flag to session request.session['OS'] = os authLogLogin(request, authenticator, user.name) return response else: form = LoginForm(tag=tag) response = render_to_response(theme.template('login.html'), {'form': form, 'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True)}, context_instance=RequestContext(request)) getUDSCookie(request, response) return response
def ticketAuth(request, ticketId): ''' Used to authenticate an user via a ticket ''' ticket = Ticket(ticketId) logger.debug('Ticket: {}'.format(ticket)) try: try: # Extract ticket.data from ticket.data storage, and remove it if success username = ticket.data['username'] groups = ticket.data['groups'] auth = ticket.data['auth'] realname = ticket.data['realname'] servicePool = ticket.data['servicePool'] password = ticket.data['password'] transport = ticket.data['transport'] except: logger.error('Ticket stored is not valid') raise InvalidUserException() # Remove ticket ticket.delete() auth = Authenticator.objects.get(uuid=auth) # If user does not exists in DB, create it right now # Add user to groups, if they exists... grps = [] for g in groups: try: grps.append(auth.groups.get(uuid=g)) except Exception: logger.debug('Group list has changed since ticket assignement') if len(grps) == 0: logger.error('Ticket has no valid groups') raise Exception('Invalid ticket authentication') usr = auth.getOrCreateUser(username, realname) if usr is None or State.isActive( usr.state) is False: # If user is inactive, raise an exception raise InvalidUserException() # Add groups to user (replace existing groups) usr.groups = grps # Right now, we assume that user supports java, let's see how this works # Force cookie generation webLogin(request, None, usr, password) request.user = usr # Temporarily store this user as "authenticated" user, next requests will be done using session # Check if servicePool is part of the ticket if servicePool is not None: servicePool = DeployedService.objects.get(uuid=servicePool) # Check if service pool can't be accessed by groups servicePool.validateUser(usr) if servicePool.isInMaintenance(): raise ServiceInMaintenanceMode() transport = Transport.objects.get(uuid=transport) response = service( request, 'F' + servicePool.uuid, transport.uuid) # 'A' Indicates 'assigned service' else: response = HttpResponsePermanentRedirect( reverse('uds.web.views.index')) # Now ensure uds cookie is at response getUDSCookie(request, response, True) return response except Authenticator.DoesNotExist: logger.error('Ticket has an non existing authenticator') return errors.error(request, InvalidUserException()) except DeployedService.DoesNotExist: logger.error('Ticket has an invalid Service Pool') return errors.error(request, InvalidServiceException()) except Exception as e: logger.exception('Exception') return errors.exceptionView(request, e)
def ticketAuth(request, ticketId): """ Used to authenticate an user via a ticket """ try: data = TicketStore.get(ticketId, invalidate=True) try: # Extract ticket.data from ticket.data storage, and remove it if success username = data['username'] groups = data['groups'] auth = data['auth'] realname = data['realname'] servicePool = data['servicePool'] password = cryptoManager().decrypt(data['password']) transport = data['transport'] except Exception: logger.error('Ticket stored is not valid') raise InvalidUserException() auth = Authenticator.objects.get(uuid=auth) # If user does not exists in DB, create it right now # Add user to groups, if they exists... grps = [] for g in groups: try: grps.append(auth.groups.get(uuid=g)) except Exception: logger.debug('Group list has changed since ticket assignment') if len(grps) == 0: logger.error('Ticket has no valid groups') raise Exception('Invalid ticket authentication') usr = auth.getOrCreateUser(username, realname) if usr is None or State.isActive(usr.state) is False: # If user is inactive, raise an exception raise InvalidUserException() # Add groups to user (replace existing groups) usr.groups.set(grps) # Force cookie generation webLogin(request, None, usr, password) request.user = usr # Temporarily store this user as "authenticated" user, next requests will be done using session request.session['ticket'] = '1' # Store that user access is done using ticket logger.debug("Service & transport: {}, {}".format(servicePool, transport)) for v in DeployedService.objects.all(): logger.debug("{} {}".format(v.uuid, v.name)) # Check if servicePool is part of the ticket if servicePool is not None: # If service pool is in there, also is transport res = userServiceManager().getService(request.user, request.ip, 'F' + servicePool, transport, False) _x, userService, _x, transport, _x = res transportInstance = transport.getInstance() if transportInstance.ownLink is True: link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid)) else: link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid) response = render( request, theme.template('simpleLauncher.html'), { 'link': link } ) else: response = HttpResponsePermanentRedirect(reverse('uds.web.views.index')) # Now ensure uds cookie is at response getUDSCookie(request, response, True) return response except ServiceNotReadyError as e: return render( request, theme.template('service_not_ready.html'), { 'fromLauncher': True, 'code': e.code } ) except TicketStore.InvalidTicket: return render( request, theme.template('simpleLauncherAlreadyLaunched.html') ) except Authenticator.DoesNotExist: logger.error('Ticket has an non existing authenticator') return errors.exceptionView(request, InvalidUserException()) except DeployedService.DoesNotExist: logger.error('Ticket has an invalid Service Pool') return errors.exceptionView(request, InvalidServiceException()) except Exception as e: logger.exception('Exception') return errors.exceptionView(request, e)
def login(request, tag=None): ''' View responsible of logging in an user :param request: http request :param tag: tag of login auth ''' # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt()) host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host' # Last one is a placeholder in case we can't locate host name # Get Authenticators limitation logger.debug('Host: {0}'.format(host)) if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True: if tag is None: try: Authenticator.objects.get(small_name=host) tag = host except Exception: try: tag = Authenticator.objects.order_by('priority')[0].small_name except Exception: # There is no authenticators yet, simply allow global login to nowhere.. :-) tag = None logger.debug('Tag: {0}'.format(tag)) logger.debug(request.method) if request.method == 'POST': if 'uds' not in request.COOKIES: logger.debug('Request does not have uds cookie') return errors.errorView(request, errors.COOKIES_NEEDED) # We need cookies to keep session data request.session.cycle_key() form = LoginForm(request.POST, tag=tag) if form.is_valid(): os = request.os try: authenticator = Authenticator.objects.get(pk=form.cleaned_data['authenticator']) except Exception: authenticator = Authenticator() userName = form.cleaned_data['user'] if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True: userName = userName.lower() cache = Cache('auth') cacheKey = str(authenticator.id) + userName tries = cache.get(cacheKey) if tries is None: tries = 0 if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt(): form.add_error(None, 'Too many authentication errors. User temporarily blocked.') authLogLogin(request, authenticator, userName, 'Temporarily blocked') else: password = form.cleaned_data['password'] user = None if password == '': password = '******' user = authenticate(userName, password, authenticator) logger.debug('User: {}'.format(user)) if user is None: logger.debug("Invalid credentials for user {0}".format(userName)) tries += 1 cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt()) form.add_error(None, ugettext('Invalid credentials')) authLogLogin(request, authenticator, userName, 'Invalid credentials') else: logger.debug('User {} has logged in'.format(userName)) cache.remove(cacheKey) # Valid login, remove cached tries response = HttpResponseRedirect(reverse('uds.web.views.index')) webLogin(request, response, user, form.cleaned_data['password']) # Add the "java supported" flag to session request.session['OS'] = os if form.cleaned_data['logouturl'] != '': logger.debug('The logoout url will be {}'.format(form.cleaned_data['logouturl'])) request.session['logouturl'] = form.cleaned_data['logouturl'] authLogLogin(request, authenticator, user.name) return response else: logger.info('Invalid form received') else: form = LoginForm(tag=tag) response = render_to_response( theme.template('login.html'), { 'form': form, 'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True), 'version': VERSION }, context_instance=RequestContext(request) ) getUDSCookie(request, response) return response
def ticketAuth(request, ticketId): """ Used to authenticate an user via a ticket """ try: data = TicketStore.get(ticketId, invalidate=True) try: # Extract ticket.data from ticket.data storage, and remove it if success username = data['username'] groups = data['groups'] auth = data['auth'] realname = data['realname'] servicePool = data['servicePool'] password = data['password'] transport = data['transport'] except Exception: logger.error('Ticket stored is not valid') raise InvalidUserException() auth = Authenticator.objects.get(uuid=auth) # If user does not exists in DB, create it right now # Add user to groups, if they exists... grps = [] for g in groups: try: grps.append(auth.groups.get(uuid=g)) except Exception: logger.debug('Group list has changed since ticket assignment') if len(grps) == 0: logger.error('Ticket has no valid groups') raise Exception('Invalid ticket authentication') usr = auth.getOrCreateUser(username, realname) if usr is None or State.isActive(usr.state) is False: # If user is inactive, raise an exception raise InvalidUserException() # Add groups to user (replace existing groups) usr.groups.set(grps) # Force cookie generation webLogin(request, None, usr, password) request.user = usr # Temporarily store this user as "authenticated" user, next requests will be done using session request.session['ticket'] = '1' # Store that user access is done using ticket logger.debug("Service & transport: {}, {}".format(servicePool, transport)) for v in DeployedService.objects.all(): logger.debug("{} {}".format(v.uuid, v.name)) # Check if servicePool is part of the ticket if servicePool is not None: # If service pool is in there, also is transport res = userServiceManager().getService(request.user, request.ip, 'F' + servicePool, transport, False) _x, userService, _x, transport, _x = res transportInstance = transport.getInstance() if transportInstance.ownLink is True: link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid)) else: link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid) response = render( request, theme.template('simpleLauncher.html'), { 'link': link } ) else: response = HttpResponsePermanentRedirect(reverse('uds.web.views.index')) # Now ensure uds cookie is at response getUDSCookie(request, response, True) return response except ServiceNotReadyError as e: return render( request, theme.template('service_not_ready.html'), { 'fromLauncher': True, 'code': e.code } ) except TicketStore.InvalidTicket: return render( request, theme.template('simpleLauncherAlreadyLaunched.html') ) except Authenticator.DoesNotExist: logger.error('Ticket has an non existing authenticator') return errors.exceptionView(request, InvalidUserException()) except DeployedService.DoesNotExist: logger.error('Ticket has an invalid Service Pool') return errors.exceptionView(request, InvalidServiceException()) except Exception as e: logger.exception('Exception') return errors.exceptionView(request, e)