def token_auth(token) -> bool: """ HTTP bearer token authorization """ jwt = JWT(current_app.config['SECRET_KEY']) try: data = jwt.loads(token) except Exception: raise AuthFailed(field='token') if data.get('consumer_id'): # todo consumer user auth ? ... else: # Normal user if ('user_id' or 'role_id') not in data: raise AuthFailed(field='token') if data['role_id'] != 1 and not data.get('tenant_uid'): raise AuthFailed(field='token') user = User.query \ .filter(User.roleIntID == data['role_id'], User.id == data['user_id'], User.tenantID == data['tenant_uid']).first() if not user: raise AuthFailed(field='token') g.user_id: int = user.id g.tenant_uid: str = user.tenantID g.role_id: int = user.roleIntID g.app_uid: str = None g.user_auth_type: int = user.userAuthType user.lastRequestTime = arrow.now().naive user.update() return True
def reset_password(): user = User.query.filter(User.id == g.user_id).first_or_404() request_dict = ResetPasswordSchema.validate_request(obj=user) _password = request_dict.get('oldPassword') if user.check_password(_password): user.lastRequestTime = datetime.now() else: raise AuthFailed(field='oldPassword') updated_user = user.update(request_dict) record = updated_user.to_dict() return jsonify(record)
def basic_auth(username, password) -> bool: """ HTTP basic authorization """ query_result = Application.query \ .join(User, User.id == Application.userIntID) \ .with_entities(Application, User) \ .filter(Application.appStatus == 1, User.enable == 1, Application.appID == username).first() if not query_result: raise AuthFailed(field='appID') application, user = query_result # Verify that app is available date_now = arrow.now().naive if application.expiredAt and date_now > application.expiredAt: raise AuthFailed(field='expiredAt') if application.appToken != password: raise AuthFailed(field='appToken') g.user_id: int = user.id g.tenant_uid: str = user.tenantID g.role_id: int = application.roleIntID g.app_uid: str = application.appID user.lastRequestTime = date_now # Update user active time user.update() return True
def device_auth(): request_form = request.form device_uid = request_form.get('device_id') cn = request_form.get('cn') connect_date = datetime.now() # query device info query = db.session \ .query(Device, func.lower(DictCode.enLabel).label('protocol')) \ .join(Product, Product.productID == Device.productID) \ .join(DictCode, DictCode.codeValue == Product.cloudProtocol) \ .filter(Device.deviceID == device_uid, Device.blocked == 0, DictCode.code == 'cloudProtocol') if cn is None or cn == 'undefined': # token auth query = query.filter(Device.authType == 1) else: # cert auth query = query \ .join(CertDevice, CertDevice.c.deviceIntID == Device.id) \ .join(Cert, Cert.id == CertDevice.c.certIntID) \ .filter(Device.authType == 2, Cert.CN == cn, Cert.enable == 1) device_info = query.first() if not device_info: raise AuthFailed(field='device') device, protocol = device_info auth_status = _validate_connect_auth(device, protocol, request_form) # insert connect_logs connect_dict = { 'IP': request_form.get('ip'), 'msgTime': connect_date, 'deviceID': device.deviceID, 'tenantID': device.tenantID } connect_log = ConnectLog() if auth_status: connect_dict['connectStatus'] = 1 device.deviceStatus = 1 device.lastConnection = connect_date record = { 'mountpoint': f'/{protocol}/{device.tenantID}/{device.productID}/{device.deviceID}/' } code = 200 else: connect_dict['connectStatus'] = 2 record, code = {'status': 401}, 401 connect_log.create(request_dict=connect_dict) return jsonify(record), code
def login(): request_dict = LoginSchema.validate_request() remember = request_dict.get('remember', False) date_now = datetime.now() query_login = db.session.query(User, Tenant) \ .outerjoin(Tenant, Tenant.tenantID == User.tenantID) \ .filter(User.email == request_dict.get('email'), User.enable == 1) \ .first() if not query_login: raise AuthFailed(field='email') user, tenant = query_login if not user or (tenant and tenant.enable != 1): raise AuthFailed(field='email') if user.expiresAt and user.expiresAt < date_now: raise AuthFailed(field='expiresAt') user.loginTime = date_now is_logged = 1 if user.check_password(request_dict.get('password')) else 0 login_log = LoginLog(userIntID=user.id, IP=request.headers.get('X-Real-Ip') or request.remote_addr, loginTime=date_now, isLogged=is_logged) db.session.add(login_log) db.session.commit() if not is_logged: raise AuthFailed(field='password') # logo path api_version = current_app.config['ACTORCLOUD_API'] logo = f'{api_version}/backend_static?fileType=image&filename=logo.png' logo_dark = f'{api_version}/backend_static?fileType=image&filename=logo-dark.png' if tenant: logo_info = db.session.query(UploadInfo.fileName) \ .filter(UploadInfo.id == tenant.logo) \ .first() logo_dark_info = db.session.query(UploadInfo.fileName) \ .filter(UploadInfo.id == tenant.logoDark) \ .first() if logo_info: logo = f'{api_version}/download?fileType=image&filename={logo_info.fileName}' if logo_dark_info: logo_dark = f'{api_version}/download?fileType=image&filename={logo_dark_info.fileName}' if isinstance(user.tenantID, str): tenant_type_dict = {'P': 1, 'C': 2} tenant_type = tenant_type_dict.get(user.tenantID[0]) else: tenant_type = 0 # Get user menu tree,tabs and permissions menus_tree, tabs, permissions = generate_tabs_and_tree( role_id=user.roleIntID, tenant_uid=user.tenantID) return jsonify({ 'userIntID': user.id, 'username': user.username, 'tenantType': tenant_type, 'tenantID': user.tenantID, 'token': user.generate_auth_token(remember=remember), 'menus': menus_tree, 'tabs': tabs, 'permissions': permissions, 'logo': logo, 'logoDark': logo_dark }), 201