def setUpClass(self): """ Create a User to link the private key to. """ u = MHLUser.objects.create(username="******") create_default_keys(u) uprivs = UserPrivateKey.objects.filter(user=u, credtype=CRED_WEBAPP, gfather=True) recrypt_keys(uprivs, self.initial_creds, self.webcreds) uprivs = UserPrivateKey.objects.filter(user=u, credtype=CRED_IVRPIN, gfather=True) recrypt_keys(uprivs, self.initial_creds, self.ivrcreds)
def change_pass_common(form, request): # TESTING_KMS_INTEGRATION uprivs = UserPrivateKey.objects.filter(user=form.user, credtype=CRED_WEBAPP, gfather=False) recrypt_keys(uprivs, form.cleaned_data['old_password'], form.cleaned_data['new_password1']) form.user.set_password(form.cleaned_data['new_password1']) form.user.force_pass_change = False form.user.save() device_assn = SmartPhoneAssn.objects.filter(user=request.user) for device in device_assn: device.usr_password_reset(request)
def change_pass(form, request, response): # TESTING_KMS_INTEGRATION uprivs = UserPrivateKey.objects.filter(user=form.user, credtype=CRED_WEBAPP, gfather=False) recrypt_keys(uprivs, form.cleaned_data['old_password'], form.cleaned_data['new_password1']) form.user.set_password(form.cleaned_data['new_password1']) form.user.save() request.session['password_change_time'] = form.user.password_change_time store_user_key(request, response, form.cleaned_data['new_password1']) device_assn = SmartPhoneAssn.objects.filter(user=request.user) for device in device_assn: device.usr_password_reset(request) return response
def change_pin(self, request, **kwargs): new_pin = kwargs.get('new_pin', None) if not new_pin: raise Exception('new_pin is required') old_key = kwargs.get('old_key', None) # TESTING_KMS_INTEGRATION from MHLogin.MHLUsers.models import MHLUser user = MHLUser.objects.get(id=self.owner.id) uprivs = UserPrivateKey.objects.filter(user=user, credtype=CRED_IVRPIN, gfather=True) if uprivs.exists(): recrypt_keys(uprivs, settings.SECRET_KEY, new_pin) elif old_key: uprivs = UserPrivateKey.objects.filter(user=user, credtype=CRED_IVRPIN) recrypt_keys(uprivs, old_key, strengthen_key(new_pin), True) else: # business logic: recrypt ivr key via user's webapp based ivr key recrypt_ivr_key_via_web_creds(user, request, new_pin) self._set_pin(new_pin) self.save()
def associate(request): logger.debug(''.join( [str(request.session.session_key), '-Request: ', str(request)])) if (request.method == 'GET'): logger.debug(''.join( [str(request.session.session_key), '-Returning GE002!!!'])) return err_GE002() form = AssociationForm(request.POST, auto_id=False) if (not form.is_valid()): return err_GE031(form) # Consider the compatibility, use the key: "allow_staff_login" -- it's optional, # distinguish different client version allow_staff_login = False if "allow_staff_login" in form.cleaned_data and form.cleaned_data[ "allow_staff_login"]: allow_staff_login = True user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if (not user): err_obj = { 'errno': 'DM001', 'descr': _('Username or password incorrect.'), } return HttpResponseBadRequest(content=json.dumps(err_obj), mimetype='application/json') # TESTING_KMS_INTEGRATION check if user is g'fathered uprivs = UserPrivateKey.objects.filter(user=user, credtype=CRED_WEBAPP, gfather=True) if uprivs.exists(): recrypt_keys(uprivs, settings.SECRET_KEY, form.cleaned_data['password']) if (not user.is_active): return err_DM002() # Okay, everything checks out. Now check that the user is a Provider or Practice Manager providers = Provider.objects.filter(user=user.id) staff = OfficeStaff.objects.filter(user__pk=user.id) mobile_phone = '' mdcom_number = '' utype = None if providers and len(providers) > 0: utype = USER_TYPE_DOCTOR mdcom_number = providers[0].mdcom_phone mobile_phone = providers[0].user.mobile_phone elif staff and len(staff) > 0: staff = staff[0] if not staff_is_active(staff): return err_DM002() if not staff.user.has_perm('MHLUsers.access_smartphone'): return err_DM005() utype = USER_TYPE_OFFICE_STAFF manager_practice = staff.current_practice if manager_practice: mdcom_number = manager_practice.mdcom_phone mobile_phone = staff.user.mobile_phone if Office_Manager.objects.filter(user=staff).exists(): utype = USER_TYPE_OFFICE_MANAGER else: if not allow_staff_login: return err_DM020() else: return err_DM020() # When user login from app, clean some assn, such as: # 1. Other user's assn in the same app client. # 2. Same user's assn in other app client. # But, one user can login one mobile device and one tablet at the same time. # Now, the platform is only three options iPhone, Android, iPad. # If available platform options changed, please change the following logic. platform = form.cleaned_data['platform'] old_assns = None if platform in ('iPhone', 'Android'): old_assns = SmartPhoneAssn.objects.filter( Q(device_serial=form.cleaned_data['device_id']) | Q(user__pk=user.pk, platform__in=('iPhone', 'Android'))) else: old_assns = SmartPhoneAssn.objects.filter( Q(device_serial=form.cleaned_data['device_id']) | Q(user__pk=user.pk, platform='iPad')) if (old_assns and old_assns.exists()): for old_assn in old_assns: old_assn.dissociate(request, True) # get/set up all necessary crypto values. password = form.cleaned_data[ 'password'] # key strengthened below in different way local, remote = split_user_key(password) # NOTE: splitkey result reversed compared to web, but we should be # OK as long as whatever deemed remote is not stored server side. db_key = os.urandom(32) xor = XOR.new(base64.b64decode(remote)) dbsplit = base64.b64encode(xor.encrypt(db_key)) # Next, create the association object assn = SmartPhoneAssn( user_id=user.pk, device_serial=form.cleaned_data['device_id'], version=form.cleaned_data['app_version'], platform=platform, user_type=utype, ) if ('name' in form.cleaned_data): assn.name = form.cleaned_data['name'] assn.save(request) assn.update_secret(local, password) assn.update_db_secret(dbsplit, db_key) response = { 'data': { 'mdcom_id': assn.device_id, 'secret': remote, 'mdcom_number': mdcom_number, 'mobile_phone': mobile_phone, 'user_id': user.pk, # about the number of user_type, please read USER_TYPE_CHOICES # in the MHLogin.utils.contants.py 'user_type': utype, 'gcm_project_id': settings.GCM_PROJECT_ID, 'call_available': settings.CALL_ENABLE and bool(mobile_phone) }, 'warnings': {}, } setSystemInfoToResponse(response) response["settings"]['prefer_logo'] = get_prefer_logo(user.pk) return HttpResponse(content=json.dumps(response), mimetype='application/json')
def login_user(request): context = RequestContext(request) context['error_msg'] = None if (request.method == 'POST'): form = LoginForm(request.POST) if request.user.is_authenticated(): logout(request) context['form'] = form if (form.is_valid()): user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if (user): if(user_is_active(user)): LoginEvent().customInit(username=form.cleaned_data['username'], \ remote_ip=request.META['REMOTE_ADDR'], success=True, \ user=user) login(request, user) request.session['password_change_time'] = MHLUser.objects.filter( pk=request.user.pk).only("password_change_time").get().password_change_time if ('next' in form.cleaned_data and form.cleaned_data['next']): response = HttpResponseRedirect(form.cleaned_data['next']) else: response = HttpResponseRedirect('/') store_user_key(request, response, form.cleaned_data['password']) # TESTING_KMS_INTEGRATION check if user is g'fathered uprivs = UserPrivateKey.objects.filter(user=user, credtype=CRED_WEBAPP, gfather=True) if uprivs.exists(): recrypt_keys(uprivs, settings.SECRET_KEY, form.cleaned_data['password']) return response else: LoginEvent().customInit(username=form.cleaned_data['username'], \ remote_ip=request.META['REMOTE_ADDR'], success=False, \ user=user) # Return a 'disabled account' error message context['error_msg'] = _("Account appears to be disabled") else: # User couldn't be found. context['error_msg'] = _("Invalid username or password") else: # Form was invalid. This shouldn't be possible. context['error_msg'] = _("Invalid username or password") # At this point, the login attempt has failed. if (settings.LOGIN_FAILED_REDIRECT): return HttpResponseRedirect(settings.LOGIN_FAILED_REDIRECT) else: # if (request.method != 'POST') if(request.user.is_authenticated()): return HttpResponseRedirect('/') next = '' if ('next' in request.GET): next = request.GET['next'] context['form'] = LoginForm(initial={'next': next}) if (settings.LOGIN_REDIRECT): return HttpResponseRedirect(settings.LOGIN_REDIRECT) context['STATIC_URL'] = ''.join([context['STATIC_URL'], 'temp/']) return render_to_response('temp/index.html', context)
def associate(request): logger.debug(''.join([str(request.session.session_key), '-Request: ', str(request)])) if (request.method == 'GET'): logger.debug(''.join([str(request.session.session_key), '-Returning GE002!!!'])) return err_GE002() form = AssociationForm(request.POST, auto_id=False) if (not form.is_valid()): return err_GE031(form) # Consider the compatibility, use the key: "allow_staff_login" -- it's optional, # distinguish different client version allow_staff_login = False if "allow_staff_login" in form.cleaned_data and form.cleaned_data["allow_staff_login"]: allow_staff_login = True user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if (not user): err_obj = { 'errno': 'DM001', 'descr': _('Username or password incorrect.'), } return HttpResponseBadRequest(content=json.dumps(err_obj), mimetype='application/json') # TESTING_KMS_INTEGRATION check if user is g'fathered uprivs = UserPrivateKey.objects.filter(user=user, credtype=CRED_WEBAPP, gfather=True) if uprivs.exists(): recrypt_keys(uprivs, settings.SECRET_KEY, form.cleaned_data['password']) if (not user.is_active): return err_DM002() # Okay, everything checks out. Now check that the user is a Provider or Practice Manager providers = Provider.objects.filter(user=user.id) staff = OfficeStaff.objects.filter(user__pk=user.id) mobile_phone = '' mdcom_number = '' utype = None if providers and len(providers) > 0: utype = USER_TYPE_DOCTOR mdcom_number = providers[0].mdcom_phone mobile_phone = providers[0].user.mobile_phone elif staff and len(staff) > 0: staff = staff[0] if not staff_is_active(staff): return err_DM002() if not staff.user.has_perm('MHLUsers.access_smartphone'): return err_DM005() utype = USER_TYPE_OFFICE_STAFF manager_practice = staff.current_practice if manager_practice: mdcom_number = manager_practice.mdcom_phone mobile_phone = staff.user.mobile_phone if Office_Manager.objects.filter(user=staff).exists(): utype = USER_TYPE_OFFICE_MANAGER else: if not allow_staff_login: return err_DM020() else: return err_DM020() # When user login from app, clean some assn, such as: # 1. Other user's assn in the same app client. # 2. Same user's assn in other app client. # But, one user can login one mobile device and one tablet at the same time. # Now, the platform is only three options iPhone, Android, iPad. # If available platform options changed, please change the following logic. platform = form.cleaned_data['platform'] old_assns = None if platform in ('iPhone', 'Android'): old_assns = SmartPhoneAssn.objects.filter(Q(device_serial=form.cleaned_data['device_id']) | Q(user__pk=user.pk, platform__in=('iPhone', 'Android'))) else: old_assns = SmartPhoneAssn.objects.filter(Q(device_serial=form.cleaned_data['device_id']) | Q(user__pk=user.pk, platform='iPad')) if (old_assns and old_assns.exists()): for old_assn in old_assns: old_assn.dissociate(request, True) # get/set up all necessary crypto values. password = form.cleaned_data['password'] # key strengthened below in different way local, remote = split_user_key(password) # NOTE: splitkey result reversed compared to web, but we should be # OK as long as whatever deemed remote is not stored server side. db_key = os.urandom(32) xor = XOR.new(base64.b64decode(remote)) dbsplit = base64.b64encode(xor.encrypt(db_key)) # Next, create the association object assn = SmartPhoneAssn( user_id=user.pk, device_serial=form.cleaned_data['device_id'], version=form.cleaned_data['app_version'], platform=platform, user_type=utype, ) if ('name' in form.cleaned_data): assn.name = form.cleaned_data['name'] assn.save(request) assn.update_secret(local, password) assn.update_db_secret(dbsplit, db_key) response = { 'data': { 'mdcom_id': assn.device_id, 'secret': remote, 'mdcom_number': mdcom_number, 'mobile_phone': mobile_phone, 'user_id': user.pk, # about the number of user_type, please read USER_TYPE_CHOICES # in the MHLogin.utils.contants.py 'user_type': utype, 'gcm_project_id': settings.GCM_PROJECT_ID, 'call_available': settings.CALL_ENABLE and bool(mobile_phone) }, 'warnings': {}, } setSystemInfoToResponse(response) response["settings"]['prefer_logo'] = get_prefer_logo(user.pk) return HttpResponse(content=json.dumps(response), mimetype='application/json')
def login_user(request): context = RequestContext(request) context['error_msg'] = None if (request.method == 'POST'): form = LoginForm(request.POST) if request.user.is_authenticated(): logout(request) context['form'] = form if (form.is_valid()): user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if (user): if (user_is_active(user)): LoginEvent().customInit(username=form.cleaned_data['username'], \ remote_ip=request.META['REMOTE_ADDR'], success=True, \ user=user) login(request, user) request.session[ 'password_change_time'] = MHLUser.objects.filter( pk=request.user.pk).only( "password_change_time").get( ).password_change_time if ('next' in form.cleaned_data and form.cleaned_data['next']): response = HttpResponseRedirect( form.cleaned_data['next']) else: response = HttpResponseRedirect('/') store_user_key(request, response, form.cleaned_data['password']) # TESTING_KMS_INTEGRATION check if user is g'fathered uprivs = UserPrivateKey.objects.filter( user=user, credtype=CRED_WEBAPP, gfather=True) if uprivs.exists(): recrypt_keys(uprivs, settings.SECRET_KEY, form.cleaned_data['password']) return response else: LoginEvent().customInit(username=form.cleaned_data['username'], \ remote_ip=request.META['REMOTE_ADDR'], success=False, \ user=user) # Return a 'disabled account' error message context['error_msg'] = _("Account appears to be disabled") else: # User couldn't be found. context['error_msg'] = _("Invalid username or password") else: # Form was invalid. This shouldn't be possible. context['error_msg'] = _("Invalid username or password") # At this point, the login attempt has failed. if (settings.LOGIN_FAILED_REDIRECT): return HttpResponseRedirect(settings.LOGIN_FAILED_REDIRECT) else: # if (request.method != 'POST') if (request.user.is_authenticated()): return HttpResponseRedirect('/') next = '' if ('next' in request.GET): next = request.GET['next'] context['form'] = LoginForm(initial={'next': next}) if (settings.LOGIN_REDIRECT): return HttpResponseRedirect(settings.LOGIN_REDIRECT) context['STATIC_URL'] = ''.join([context['STATIC_URL'], 'temp/']) return render_to_response('temp/index.html', context)