def on_confirm(self): password = LoginUser.hash(self.model.password) current_branch = api.get_current_branch(self.store) try: self.retval = LoginUser.authenticate(self.store, self.model.username, password, current_branch) except LoginError as e: self.retval = None warning(str(e))
def test_get_active_users(self): active_users_count = LoginUser.get_active_users(self.store).count() user = self.create_user() active_users = LoginUser.get_active_users(self.store) self.assertTrue(user in active_users) self.assertEqual(active_users.count(), active_users_count + 1) user.inactivate() active_users = LoginUser.get_active_users(self.store) self.assertFalse(user in active_users) self.assertEqual(active_users.count(), active_users_count)
def cookie_login(self): if api.sysparam.get_bool('DISABLE_COOKIES'): log.info("Cookies disable by parameter") return cookie_file = get_utility(ICookieFile) try: username, password = cookie_file.get() except CookieError: log.info("Not using cookie based login") return def is_md5(password): # This breaks for passwords that are 32 characters long, # uses only digits and lowercase a-f, pretty unlikely as # real-world password if len(password) != 32: return False for c in '1234567890abcdef': password = password.replace(c, '') return password == '' # Migrate old passwords to md5 hashes. if not is_md5(password): password = LoginUser.hash(password) cookie_file.store(username, password) try: user = self._check_user(username, password) except (LoginError, UserProfileError, DatabaseError) as e: log.info("Cookie login failed: %r" % e) return log.info("Logging in using cookie credentials") return user
def create_model(self, store): person = BasePersonRoleEditor.create_model(self, store) return person.login_user or LoginUser(person=person, store=store, username=u"", password=u"", profile=None)
def test_default_receiving_cfop(self): branch = self.create_branch() param = self.sparam.get_object(self.store, 'DEFAULT_RECEIVING_CFOP') person = Person(name=u'Craudinho', store=self.store) Individual(person=person, store=self.store) profile = UserProfile(name=u'profile', store=self.store) responsible = LoginUser(person=person, store=self.store, password=u'asdfgh', profile=profile, username=u'craudio') receiving_order = ReceivingOrder(responsible=responsible, branch=branch, store=self.store, invoice_number=876, supplier=None) param2 = self.sparam.get_object(self.store, 'DEFAULT_SALES_CFOP') receiving_order2 = ReceivingOrder(responsible=responsible, cfop=param2, branch=branch, store=self.store, invoice_number=1231, supplier=None) self.assertEqual(param, receiving_order.cfop) self.failIfEqual(param, receiving_order2.cfop)
def _check_user(self, username, pw_hash): username = unicode(username) pw_hash = unicode(pw_hash) # This function is really just a post-validation item. default_store = api.get_default_store() current_branch = api.get_current_branch(default_store) user = LoginUser.authenticate(default_store, username, pw_hash, current_branch) # Dont know why, but some users have this empty. Prevent user from # login in, since it will break later if not user.profile: msg = (_("User '%s' has no profile set, " "but this should not happen.") % user.username + '\n\n' + _("Please contact your system administrator or Stoq team.")) warning(msg) raise LoginError(_("User does not have a profile")) user.login() # ICurrentUser might already be provided which is the case when # creating a new database, thus we need to replace it. provide_utility(ICurrentUser, user, replace=True) return user
def _check_user(self, username, pw_hash): username = str(username) pw_hash = str(pw_hash) # This function is really just a post-validation item. default_store = api.get_default_store() current_branch = api.get_current_branch(default_store) user = LoginUser.authenticate(default_store, username, pw_hash, current_branch) # Dont know why, but some users have this empty. Prevent user from # login in, since it will break later if not user.profile: msg = (_("User '%s' has no profile set, " "but this should not happen.") % user.username + '\n\n' + _("Please contact your system administrator or Stoq team.")) warning(msg) raise LoginError(_("User does not have a profile")) user.login() # ICurrentUser might already be provided which is the case when # creating a new database, thus we need to replace it. provide_utility(ICurrentUser, user, replace=True) return user
def create_user(self, username=u'username'): from stoqlib.domain.person import LoginUser individual = self.create_individual() profile = self.create_user_profile() return LoginUser(person=individual.person, username=username, password=u'password', profile=profile, store=self.store)
def requestAvatarId(self, credentials): with api.new_store() as store: try: login_ok = LoginUser.authenticate( store, unicode(credentials.username), unicode(credentials.password), None) except LoginError as err: return defer.fail(cred_error.UnauthorizedLogin(str(err))) assert login_ok return defer.succeed(credentials.username)
def post(self): username = self.get_arg('user') pw_hash = self.get_arg('pw_hash') with api.new_store() as store: try: # FIXME: Respect the branch the user is in. user = LoginUser.authenticate(store, username, pw_hash, current_branch=None) provide_utility(ICurrentUser, user, replace=True) except LoginError as e: abort(403, str(e)) return user.id
def _do_login(self): username = unicode(self.username.get_text().strip()) password = unicode(self.password.get_text().strip()) password = LoginUser.hash(password) self.retval = username, password self.set_field_sensitivity(False) self.notification_label.set_color('black') msg = _(" Authenticating user...") self.notification_label.set_text(msg) while gtk.events_pending(): gtk.main_iteration() gtk.main_quit() self.set_field_sensitivity(True)
def _do_login(self): username = str(self.username.get_text().strip()) password = str(self.password.get_text().strip()) password = LoginUser.hash(password) self.retval = username, password self.set_field_sensitivity(False) self.notification_label.set_color('black') msg = _(" Authenticating user...") self.notification_label.set_text(msg) while Gtk.events_pending(): Gtk.main_iteration() Gtk.main_quit() self.set_field_sensitivity(True)
def get(self, store): data = request.args request_is_active = data.get('ativo') users = store.find(LoginUser) if request_is_active == '1': users = LoginUser.get_active_users(store) elif request_is_active == '0': users = users.find(is_active=False) network = _get_network_info() response = [] for user in users: person_names = _get_person_names(user.person) profile = user.profile response.append({ 'id': user.id, 'codigo': user.username, 'dataCriacao': user.te.te_time.strftime('%Y-%m-%d %H:%M:%S -0300'), 'dataAlteracao': user.te.te_server.strftime('%Y-%m-%d %H:%M:%S -0300'), 'primeiroNome': person_names['primeiroNome'], 'segundoNome': person_names['segundoNome'], 'sobrenome': person_names['sobrenome'], 'apelido': person_names['apelido'], # FIXME: Assert every one has profile in database or # create a default profile for all? 'idCargo': profile.id if profile else None, 'codCargo': profile.id if profile else None, 'nomeCargo': profile.name if profile else None, 'redeId': network['id'], 'lojaId': None, 'ativo': user.is_active, }) return response
def post(self, store): username = self.get_arg('user') pw_hash = self.get_arg('pw_hash') permission = self.get_arg('permission') try: # FIXME: Respect the branch the user is in. user = LoginUser.authenticate(store, username, pw_hash, current_branch=None) except LoginError as e: return make_response(str(e), 403) if user.profile.check_app_permission(permission): return True return make_response(_('User does not have permission'), 403)
def ensure_admin_user(administrator_password): log.info("Creating administrator user") default_store = get_default_store() user = get_admin_user(default_store) if user is None: store = new_store() person = Person(name=_(u'Administrator'), store=store) # Dependencies to create an user. role = EmployeeRole(name=_(u'System Administrator'), store=store) Individual(person=person, store=store) employee = Employee(person=person, role=role, store=store) EmployeeRoleHistory(store=store, role=role, employee=employee, is_active=True, salary=currency(800)) # This is usefull when testing a initial database. Admin user actually # must have all the facets. SalesPerson(person=person, store=store) profile = store.find(UserProfile, name=_(u'Administrator')).one() # Backwards compatibility. this profile used to be in english # FIXME: Maybe its safe to assume the first profile in the table is # the admin. if not profile: profile = store.find(UserProfile, name=u'Administrator').one() log.info("Attaching a LoginUser (%s)" % (USER_ADMIN_DEFAULT_NAME, )) LoginUser(person=person, username=USER_ADMIN_DEFAULT_NAME, password=administrator_password, profile=profile, store=store) store.commit(close=True) # Fetch the user again, this time from the right connection user = get_admin_user(default_store) assert user user.set_password(administrator_password) # We can't provide the utility until it's actually in the database log.info('providing utility ICurrentUser') provide_utility(ICurrentUser, user)
def process_one(self, data, fields, store): person = Person( store=store, name=data.name, phone_number=data.phone_number, mobile_number=data.mobile_number) Individual(person=person, store=store, cpf=data.cpf, rg_number=data.rg) role = EmployeeRole(store=store, name=data.role) employee = Employee(person=person, store=store, role=role, salary=int(data.salary), registry_number=data.employee_number) start = self.parse_date(data.start) EmployeeRoleHistory( store=store, role=role, employee=employee, is_active=True, began=start, salary=int(data.salary)) ctloc = CityLocation.get_or_create(store=store, city=data.city, state=data.state, country=data.country) streetnumber = data.streetnumber and int(data.streetnumber) or None Address(is_main_address=True, person=person, city_location=ctloc, store=store, street=data.street, streetnumber=streetnumber, district=data.district) if self.create_users: profile = store.find(UserProfile, name=data.profile).one() LoginUser(person=person, store=store, profile=profile, username=data.username, password=data.password) SalesPerson(person=person, store=store)
def do_GET(self): auth = self.headers.getheader('Authorization') if not auth or not auth.startswith('Basic '): self.do_AUTHHEAD() self.wfile.write('Missing authentication') return encoded_auth = auth.replace('Basic ', '') username, password = base64.b64decode(encoded_auth).split(':') with api.new_store() as store: try: login_ok = LoginUser.authenticate( store, str(username), str(password), None) except LoginError: login_ok = False if not login_ok: self.send_error(403, "User not found") return return http.server.SimpleHTTPRequestHandler.do_GET(self)
def do_GET(self): auth = self.headers.getheader('Authorization') if not auth or not auth.startswith('Basic '): self.do_AUTHHEAD() self.wfile.write('Missing authentication') return encoded_auth = auth.replace('Basic ', '') username, password = base64.b64decode(encoded_auth).split(':') with api.new_store() as store: try: login_ok = LoginUser.authenticate(store, unicode(username), unicode(password), None) except LoginError: login_ok = False if not login_ok: self.send_error(403, "User not found") return return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def _fill_execution_responsible_combo(self): users = LoginUser.get_active_users(self.store) self.execution_responsible.prefill(api.for_person_combo(users))
def validate_user(self): """ Checks if an user can log in or not. :returns: a user object """ # If there is only one user, and that user is admin with a blank # password, just log the user in store = api.get_default_store() if store.find(LoginUser).count() == 1: try: return self._check_user(u'admin', LoginUser.hash(u'')) except Exception: pass log.info("Showing login dialog") # Loop for logins retry = 0 retry_msg = None dialog = None while retry < RETRY_NUMBER: username = self._force_username password = None if not dialog: dialog = LoginDialog(_("Stoq - Access Control")) if self._force_username: dialog.force_username(username) ret = dialog.run(username, password, msg=retry_msg) # user cancelled (escaped) the login dialog if not ret: return # Use credentials if not (isinstance(ret, (tuple, list)) and len(ret) == 2): raise ValueError('Invalid return value, got %s' % str(ret)) username, password = ret if not username: retry_msg = _("specify an username") continue try: user = self._check_user(username, password) except (LoginError, UserProfileError) as e: # We don't hide the dialog here; it's kept open so the # next loop we just can call run() and display the error cookie = get_utility(ICookieFile, None) if cookie: cookie.clear() retry += 1 retry_msg = str(e) except DatabaseError as e: if dialog: dialog.destroy() self._abort(str(e)) else: log.info("Authenticated user %s" % username) self._force_username = None if dialog.remember.get_active(): get_utility(ICookieFile).store(user.username, user.pw_hash) if dialog: dialog.destroy() return user if dialog: dialog.destroy() raise LoginError(_("Depleted attempts of authentication"))