text
stringlengths
0
1.05M
meta
dict
# auth0login/auth0backend.py from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 from accounts.models import UserProfile class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('picture', 'picture'), ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): """Return current user id.""" print("is this using user ID?") print("user id: {}".format(details['user_id'])) return details['user_id'] def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') # CLIENT_ID payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': payload['nickname'], 'first_name': payload['name'], 'picture': payload['picture'], 'user_id': payload['sub'], 'email': payload['email']}
{ "repo_name": "chop-dbhi/biorepo-portal", "path": "auth0login/auth0backend.py", "copies": "1", "size": "1536", "license": "bsd-2-clause", "hash": 3260646804566734000, "line_mean": 33.9090909091, "line_max": 107, "alpha_frac": 0.595703125, "autogenerated": false, "ratio": 3.773955773955774, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9867410538154782, "avg_score": 0.00044967216019847593, "num_lines": 44 }
"""Auth Adapter Template File IMPORTANT: NOT A FUNCTIONAL ADAPTER. FUNCTIONS MUST BE IMPLEMENTED Notes: - Each of the functions defined below must return a json serializable object, json_response, or valid HttpResponse object - A json_response creates an HttpResponse object given parameters: - content: string with the contents of the response - status: string with the status of the response - status_code: HTTP status code - error: string with the error message if there is one """ from common.response import json_response import logging import re logger = logging.getLogger("newt." + __name__) def get_status(request): """Returns the current user status Keyword arguments: request -- Django HttpRequest """ pass def login(request): """Logs the user in and returns the status Keyword arguments: request -- Django HttpRequest """ pass def logout(request): """Logs the user out and returns the status Keyword arguments: request -- Django HttpRequest """ pass """A tuple list in the form of: ( (compiled_regex_exp, associated_function, request_required), ... ) Note: The compiled_regex_exp must have named groups corresponding to the arguments of the associated_function Note: if request_required is True, the associated_function must have request as the first argument Example: patterns = ( (re.compile(r'/usage/(?P<path>.+)$'), get_usage, False), (re.compile(r'/image/(?P<query>.+)$'), get_image, False), (re.compile(r'/(?P<path>.+)$'), get_resource, False), ) """ patterns = ( ) def extras_router(request, query): """Maps a query to a function if the pattern matches and returns result Keyword arguments: request -- Django HttpRequest query -- the query to be matched against """ for pattern, func, req in patterns: match = pattern.match(query) if match and req: return func(request, **match.groupdict()) elif match: return func(**match.groupdict()) # Returns an Unimplemented response if no pattern matches return json_response(status="Unimplemented", status_code=501, error="", content="query: %s" % query)
{ "repo_name": "NERSC/newt-2.0", "path": "authnz/adapters/template_adapter.py", "copies": "3", "size": "2418", "license": "bsd-2-clause", "hash": -3853432754423345700, "line_mean": 27.1279069767, "line_max": 75, "alpha_frac": 0.6244830438, "autogenerated": false, "ratio": 4.545112781954887, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6669595825754887, "avg_score": null, "num_lines": null }
"""Auth API endpoints.""" from flask import g, url_for, request from flask_smorest import abort, Blueprint from flask_login import login_required, logout_user from bookmarks import csrf, db, utils from bookmarks.users.models import User from .schemas import UserPOSTSchema, TokenSchema, RequestPasswordResetSchema, ResetPasswordSchema from .utils import is_recaptcha_valid auth_api = Blueprint('auth_api', 'Auth', url_prefix='/api/v1/auth/', description='Endpoints for logging in/out etc') @auth_api.route('/request-token', methods=['POST']) @csrf.exempt @login_required def request_token(): """Return new token for the user.""" if not g.user.active: abort(403, message='Email address is not verified yet.') token = g.user.generate_auth_token() g.user.auth_token = token db.session.add(g.user) db.session.commit() return {'token': token} @auth_api.route('/confirm') @auth_api.arguments(TokenSchema, location='query') @csrf.exempt def confirm(args): data = User.verify_auth_token(args['token']) user = User.query.get(data['id']) if data.get('id') else None if user is None: abort(409, message='Confirmation link is invalid or has expired.') if 'email' in data: # user tried to update profile user_exists = User.query.filter_by(email=data['email']).scalar() if user_exists: abort(409, message='Email is already taken') user.email = data['email'] user.authenticated = False db.session.add(user) db.session.commit() logout_user() return {'message': ('Email updated successfully. You can now login with the new ' 'email address.')}, 200 if user.active: return {'message': 'Your account is already activated, please login.'}, 200 user.active = True db.session.add(user) db.session.commit() return {'message': 'Your account has been activated. You can now login.'}, 200 @auth_api.route('/logout') @csrf.exempt @login_required def logout(): """Logout a user.""" g.user.auth_token = '' g.user.authenticated = False logout_user() db.session.commit() return {}, 204 @auth_api.route('/register', methods=['POST']) @csrf.exempt @auth_api.arguments(UserPOSTSchema) def register(args): user = db.session.query(User).filter( (User.username == args['username']) | (User.email == args['email'])).first() if user and user.username == args['username'] and \ user.email == args['email']: abort(409, message='Username and email are already taken') if user and user.username == args['username']: abort(409, message='Username is already taken') if user and user.email == args['email']: abort(409, message='Email is already taken') if not is_recaptcha_valid(args['recaptcha']): abort(409, message="Recaptcha verification failed") user = User(username=args['username'], email=args['email'], password=args['password']) db.session.add(user) db.session.commit() user.auth_token = user.generate_auth_token() db.session.add(user) db.session.commit() activation_link = url_for('auth_api.confirm', token=user.auth_token, _external=True) text = (f'Welcome {user.username},\n\nactivate your account by clicking this' f' link: {activation_link}') utils.send_email('Account confirmation - PyBook', user.email, text) return {'message': ('A verification email has been sent to the registered ' 'email address. Please follow the instructions to verify' ' your email address.')}, 200 @auth_api.route('/request-password-reset', methods=['POST']) @csrf.exempt @auth_api.arguments(RequestPasswordResetSchema) def request_password_reset(args): response = {'message': ('If your email address exists in our database, you will receive a ' 'password recovery link at your email address.')}, 200 user = User.query.filter_by(email=args['email']).scalar() if user is None: return response user.auth_token = user.generate_auth_token() activation_link = url_for('index', token=user.auth_token, _external=True) text = ( f'Hello {user.username},\n\nSomeone, hopefully you, has requested to reset ' f'the password for\nyour PyBook account on {request.host_url}.\nIf you did not ' 'perform this request, you can safely ignore this email.\n' f'Otherwise, click the link below to complete the process.\n{activation_link}#/reset-password' ) utils.send_email('Reset password instructions', user.email, text) db.session.add(user) db.session.commit() return response @auth_api.route('/reset-password', methods=['POST']) @csrf.exempt @auth_api.arguments(ResetPasswordSchema) def reset_password_post(args): token = request.args.get('token', '') data = User.verify_auth_token(token) user = User.query.get(data['id']) if data and data.get('id') else None if not all([data, user]): abort(409, message='Your password reset link is invalid or has expired.') user.password = args['password'] db.session.add(user) db.session.commit() text = ( f'Hello {user.username},\nThe password for your PyBook account on {request.host_url}' ' has successfully been changed.\nIf you did not initiate this change, ' 'please contact your \nadministrator immediately.' ) utils.send_email('Password changed', user.email, text)
{ "repo_name": "ev-agelos/Python-bookmarks", "path": "bookmarks/api/auth.py", "copies": "1", "size": "5611", "license": "mit", "hash": 2227816919678489600, "line_mean": 35.6732026144, "line_max": 102, "alpha_frac": 0.6524683657, "autogenerated": false, "ratio": 3.824812542603954, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4977280908303954, "avg_score": null, "num_lines": null }
# Auth codes data_auth = "TESTAUTHCODE" data_auth_admin = "TESTAUTHADMINCODE" data_accounts_post_good = { "api_key": data_auth_admin, "username": "mike+testpromopuffin@westerncapelabs.com", "password": "testweak" } data_accounts_put_good = { # "api_key": data_auth_admin, "username": "user1@example.com", "password": "testweak" } data_accounts_login_good = { "username": "user1@example.com", "password": "bcryptedhash", } data_accounts_login_bad = { "username": "user1@example.com", "password": "sdfskldfjskldjf", } data_accounts_data = { "uuid_1": { "username": "user1@example.com", "password": "bcryptedhash", "api_key": "thisandthat", }, "uuid_2": { "username": "user2@example.com", "password": "bcryptedhash", "api_key": "thisandthat", }, "uuid_3": { "username": "user3@example.com", "password": "bcryptedhash", "api_key": "thisandthat", }, } data_campaigns_post_good = { "name": "OneTheWayCampaign", "start": "2013-05-21T19:12:04.781440", "end": "2013-05-21T19:12:04.781462", "account_id": "uuid_1", } data_campaigns_put_good = { "name": "OneTheWayCampaign", "start": "2013-05-21T19:12:04.781440", "end": "2013-06-21T19:12:04.781462", "account_id": "uuid_1", } data_campaigns_put_bad = { "name": "OneTheWayCampaign", "start": "2013-05-21T19:12:04.781440", "end": "2013-04-21T19:12:04.781462", "account_id": "uuid_1", } data_campaigns_data = { "uuid_1": { "name": "Campaign1", "start": "2013-05-21T19:12:04.781440", "end": "2013-05-21T19:12:04.781462", "account_id": "uuid_1", }, "uuid_2": { "name": "Campaign2", "start": "2013-05-21T19:12:04.781440", "end": "2013-05-21T19:12:04.781462", "status": "running", "account_id": "uuid_2", }, "uuid_3": { "name": "Campaign3", "start": "2013-05-21T19:12:04.781440", "end": "2013-05-21T19:12:04.781462", "account_id": "uuid_3", }, } data_campaigns_status_post_good = { "name": "Campaign1", "start": "2013-05-21T19:12:04.781440", "end": "2013-05-21T19:12:04.781462", "account_id": "uuid_1", "status": "halted", } data_campaigns_codes_data = { "uuid_1": { 'campaign_id': 'uuid_1', 'code': 'ACT-EKL-ABCDEF', 'friendly_code': 'FREESHIPPING', "description": "A friendly name of the code", "status": "available", "value_type": "percentage", "value_amount": 50.00, "value_currency": "ZAR", "minimum": 250.00, "minimum_currency": "ZAR", "total": 50, "history_msg": [], "remaining": 28, }, "uuid_2": { 'campaign_id': 'uuid_2', 'code': 'ACT-EMD-ABCOSX', 'friendly_code': 'FREESHIPPING', "description": "A friendly name of the code", "status": "unused", "value_type": "fixed", "value_amount": 50.00, "value_currency": "ZAR", "minimum": 250.00, "minimum_currency": "ZAR", "total": 50, "history_msg": [], "remaining": 0, }, "uuid_3": { 'campaign_id': 'uuid_3', 'code': 'QWZ-EMD-ABCDEF', 'friendly_code': 'FREESHIPPING', "description": "A friendly name of the code", "status": "available", "value_type": "fixed", "value_amount": 50.00, "value_currency": "ZAR", "minimum": 250.00, "minimum_currency": "ZAR", "total": 50, "history_msg": [], "remaining": 28, }, } data_campaigns_codes_post_good = { 'campaign_id': 'uuid_1', 'code': 'ABC-DEF-GIJKLM', 'friendly_code': 'DISCOUNTS', "description": "A friendly name of the code", "status": "availiable", "value_type": "fixed", "value_amount": 50.00, "value_currency": "ZAR", "minimum": 250.00, "minimum_currency": "ZAR", "total": 50, "remaining": 28, } data_campaigns_codes_put_good = { 'campaign_id': 'uuid_1', 'code': 'ABC-DEF-GIJKLM', 'friendly_code': 'DISCOUNTS', "description": "A friendly name of the code", "status": "redeemed", "value_type": "fixed", "value_amount": 50.00, "value_currency": "ZAR", "minimum": 250.00, "minimum_currency": "ZAR", "total": 50, "remaining": 28, } data_validation_post_percentage_good = { 'code_id': "uuid_3", 'api_key': "thisandthat", "code": "QWZ-EMD-ABCDEF", "friendly_code": "FREESHIPPING", "transaction_amount": 500.00, "transaction_currency": "ZAR", } data_validation_post_fixed_good = { 'code_id': "uuid_2", 'api_key': "thisandthat", "code": "ACT-EMD-ABCOSX", "friendly_code": "FREESHIPPING", "transaction_amount": 500.00, "transaction_currency": "ZAR", } data_validation_post_bad = { 'code_id': "uuid_1", 'api_key': "dsfjskdfjsl", "code": "ACT-EKL-ABEDTF", "friendly_code": "FREESHIPPING", "transaction_amount": 500.00, "transaction_currency": "USD", } data_redeem_percentage_good = { 'code_id': "uuid_3", 'api_key': "thisandthat", "code": "QWZ-EMD-ABCDEF", "friendly_code": "FREESHIPPING", "transaction_amount": 500.00, "transaction_currency": "ZAR", } data_redeem_percentage_bad = { 'code_id': "uuid_2", 'api_key': "thisandthat", "code": "ACT-EMD-ABCOSX", "friendly_code": "FREESHIPPING", "transaction_amount": 500.00, "transaction_currency": "ZAR", } data_redeem_fixed_good = { 'code_id': "uuid_3", 'api_key': "thisandthat", "code": "QWZ-EMD-ABCDEF", "friendly_code": "FREESHIPPING", "transaction_amount": 500.00, "transaction_currency": "ZAR", }
{ "repo_name": "westerncapelabs/promopuffin-core", "path": "web/test_data.py", "copies": "1", "size": "5797", "license": "bsd-3-clause", "hash": 8168935843591968000, "line_mean": 24.6504424779, "line_max": 59, "alpha_frac": 0.5511471451, "autogenerated": false, "ratio": 2.785679961556944, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.8836827106656944, "avg_score": 0, "num_lines": 226 }
""" Auth decorator """ import functools from flask import request, Response, session from frontui.data_provider import DataProvider from frontui.linq import first_or_default def check_auth(username, password): """ Checks credentials """ database = DataProvider() current_user = first_or_default(database.users, lambda x: x.username == username) if current_user is None: return False if current_user.password != password: return False session['user_name'] = current_user.username session['user_role'] = current_user.rolename return True def authenticate(): """ Sends 401 response """ return Response( 'Требуется авторизация\n' 'Укажите имя пользователя и пароль', 401, {'WWW-Authenticate': 'Basic realm="SecretShopper"'} ) def authorize(route): """ Auth decorator """ @functools.wraps(route) def decorated(*args, **kwargs): """ Decorate request """ auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return route(*args, **kwargs) return decorated
{ "repo_name": "nixxa/SecretShopper", "path": "frontui/auth.py", "copies": "1", "size": "1212", "license": "mit", "hash": -7386493876062698000, "line_mean": 29.6052631579, "line_max": 85, "alpha_frac": 0.6560619089, "autogenerated": false, "ratio": 3.788273615635179, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49443355245351794, "avg_score": null, "num_lines": null }
"""auth_demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from accounts import views as accounts_views from hello import views as hello_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', hello_views.get_index, name='index'), url(r'^register/$', accounts_views.register, name='register'), url(r'^login/$', accounts_views.login, name='login'), url(r'^profile/$', accounts_views.profile, name='profile'), url(r'^logout/$', accounts_views.logout, name='logout'), ]
{ "repo_name": "GunnerJnr/_CodeInstitute", "path": "Stream-3/Full-Stack-Development/10.Custom-User-And-Email-Authentication/5.Handling-Authentication/auth_demo/auth_demo/urls.py", "copies": "2", "size": "1153", "license": "mit", "hash": -210700132109033950, "line_mean": 40.1785714286, "line_max": 79, "alpha_frac": 0.6929748482, "autogenerated": false, "ratio": 3.558641975308642, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5251616823508641, "avg_score": null, "num_lines": null }
# /auth/(douban|weibo) import web from util import login,oauth from model import user from config.setting import blankrender class auth: def GET(self,name): input = web.input() new_user = None cur_user = login.logged() try: client = oauth.createClientWithName(name) access_token = client.get_access_token(input["code"]) user_info = client.get_current_user_info(access_token) user_info["access_token"] = access_token if cur_user: user.update_oauth_userid(name,cur_user["id"],user_info["id"]) user.update_access_token(name,user_info["id"],access_token) if not cur_user: oauth_user = user.exist_oauth_user(name,user_info) if not oauth_user: new_user = user.new_oauth_user(name,user_info) else: user.update_access_token(name,oauth_user[name+"_id"],access_token) user.login_oauth_user(name,user_info) return blankrender.logged(True,new_user) except Exception: return blankrender.logged(True,None)
{ "repo_name": "supersheep/huixiang", "path": "controller/page/auth.py", "copies": "1", "size": "1186", "license": "mit", "hash": -2580181706532925000, "line_mean": 33.8823529412, "line_max": 86, "alpha_frac": 0.5741989882, "autogenerated": false, "ratio": 3.8758169934640523, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4950015981664052, "avg_score": null, "num_lines": null }
"""authenticated registries Revision ID: 4c22f218654 Revises: 20d5bd63d3d Create Date: 2015-11-16 11:17:19.479593 """ # revision identifiers, used by Alembic. revision = '4c22f218654' down_revision = '20d5bd63d3d' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('authenticated_registry', sa.Column('id', sa.Integer(), nullable=False), sa.Column('display_name', sa.String(length=255), nullable=False), sa.Column('base_name', sa.String(length=255), nullable=False), sa.Column('username', sa.String(length=255), nullable=True), sa.Column('password', sa.String(length=255), nullable=True), sa.Column('email', sa.String(length=255), nullable=True), sa.Column('insecure', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('display_name') ) op.create_index(op.f('ix_authenticated_registry_base_name'), 'authenticated_registry', ['base_name'], unique=True) op.add_column('project', sa.Column('target_registry_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'project', 'authenticated_registry', ['target_registry_id'], ['id']) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'project', type_='foreignkey') op.drop_column('project', 'target_registry_id') op.drop_index(op.f('ix_authenticated_registry_base_name'), table_name='authenticated_registry') op.drop_table('authenticated_registry') ### end Alembic commands ###
{ "repo_name": "RickyCook/DockCI", "path": "alembic/versions/4c22f218654_authenticated_registries.py", "copies": "2", "size": "1665", "license": "isc", "hash": 2427125460051402000, "line_mean": 36.8409090909, "line_max": 118, "alpha_frac": 0.6966966967, "autogenerated": false, "ratio": 3.4472049689440993, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00870742800863626, "num_lines": 44 }
"""Authenticate Module.""" import sys import requests from Common import Common class Authenticate(Common): """ Authenticate class. This class performs user login (authentication), and returns the session object. This session object is further used to get other details. """ def __init__(self): """Initialisations.""" Common.__init__(self) self.url = "https://amizone.net" self.login_url = "https://amizone.net/amizone/Index.aspx" self.session = requests.Session() self.payload = {} self.soup = self.get_html(self.session, self.url) def set_payload(self, username, password): """ set_payload method. `payload` is the data to be sent to perform login. `payload` includes hidden form data, username, password. `payload` here is a dictationary [{"key":"value"}] """ # Get `hidden` form data for i in self.soup.find_all("input", {'type':'hidden'}): self.payload[i['name']] = i['value'] """ Amizone has multiple username/password input fields and selects any one at random. The field being used is detected, and used to perform login. Eg: <input name="mifrd3qj3rca5o3dw243he" type="text" id="mifrd3qj3rca5o3dw243he" style="display:none;"> <input name="nyrfgj2kn4cf51c4onujcb" type="text" id="nyrfgj2kn4cf51c4onujcb" style="display:none;"> <input name="yx3llru2bl2kd4jzoi5djf" type="text" id="yx3llru2bl2kd4jzoi5djf"> The field in use is one with no `style` attribute. """ uname_fields = self.soup.find_all('div', class_='form-elements')[1].find_all('input') password_fields = self.soup.find_all('div', class_='form-elements')[2].find_all('input') for uname_id in uname_fields: if not uname_id.has_attr('style'): self.payload[uname_id['id']] = username else: self.payload[uname_id['id']] = "" for password_id in password_fields: if not password_id.has_attr('style'): self.payload[password_id['id']] = password else: self.payload[password_id['id']] = "" """ ImgBttn_Login is the login button on amizone.net. It's .x and .y values are the co-ordinate positions of mouse-pointer where button is clicked. Setting it to 0 means `enter` key is pressed. """ self.payload["ImgBttn_Login.x"] = 0 self.payload["ImgBttn_Login.y"] = 0 # Other misc. data required to be sent to perform login self.payload['__EVENTTARGET'] = "" self.payload['__EVENTARGUMENT'] = "" def login(self, username, password): """ Once payload is set, we perform login. session.post(url, data, headers) """ self.set_payload(username, password) print("Logging in...") a = self.session.post(self.login_url, data=self.payload, headers={'Referer': self.login_url}) if a.history == []: print("Incorrect Username/Password! Try Again.\n") sys.exit(2) return self.session if __name__ == "__main__": print("It's a module!")
{ "repo_name": "kryptxy/cli-amizone", "path": "amizone/Authenticate.py", "copies": "1", "size": "3267", "license": "mit", "hash": -7423692243773564000, "line_mean": 34.1290322581, "line_max": 107, "alpha_frac": 0.5904499541, "autogenerated": false, "ratio": 3.7294520547945207, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4819902008894521, "avg_score": null, "num_lines": null }
"""Authenticate Single Sign-On Middleware ============== Single-Sign On ============== About SSO --------- Single sign on is a session/user authentication process that allows a user to provide his or her credentials once in order to access multiple applications. The single sign on authenticates the user to access all the applications he or she has been authorized to access. It eliminates future authenticaton requests when the user switches applications during that particular session. .. admonition :: sources # http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci340859,00.html # http://en.wikipedia.org/wiki/Single_sign-on AuthKit Implementations ----------------------- The SSO sub-package of Authenticate implements various SSO schemes for several University SSO systems as well as OpenID. In the future, additional SSO schemes like LID may also be supported. These systems sub-class the ``RedirectingAuthMiddleware`` from the api package as they all utilize a similar scheme of authentcation via redirection with back-end verification. .. note:: All University SSO work developed by Ben Bangert has been sponsered by Prometheus Research, LLC and contributed under the BSD license. """
{ "repo_name": "santisiri/popego", "path": "envs/ALPHA-POPEGO/lib/python2.5/site-packages/AuthKit-0.4.0-py2.5.egg/authkit/authenticate/sso/__init__.py", "copies": "3", "size": "1230", "license": "bsd-3-clause", "hash": 7468298428619605000, "line_mean": 34.1428571429, "line_max": 81, "alpha_frac": 0.7552845528, "autogenerated": false, "ratio": 4.22680412371134, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.648208867651134, "avg_score": null, "num_lines": null }
"""Authentication against the Facebook ouath2 api.""" import urllib, urlparse, json import base import rowan.controllers as controllers import rowan.http as http FACEBOOK_OAUTH = { # These should be fine, unless Facebook changes its API "host": "graph.facebook.com", "user_authorization": "/oauth/authorize", "access_token": "/oauth/access_token", "profile": "/me", } class FacebookOAuthError(Exception): pass class FacebookAuthChannel(base.AuthChannel): """ Encapsulates the handling of Facebook's authentication data and its storage in a database. """ def get_channel_key(self): return "facebook" def create_session_data(self): return { 'access_token': self.data['access_token'], 'permissions': self.data['permissions'] } def create_user_data(self): return { 'user_id': self.data['uid'], 'user_name': self.data['name'] } def create_auth_data(self): return { "facebook_id": self.data['uid'] } def get_auth_data(self, db): auth_table_name = self.get_auth_table_name() return db[auth_table_name].find_one( {'facebook_id': self.data['uid']} ) def facebook_begin_auth(request): """ Initiate the authentication against the Facebook oauth2 server. """ # Redirect the user to the Facebook login screen host = FACEBOOK_OAUTH['host'] action = FACEBOOK_OAUTH['user_authorization'] params = dict( client_id=request.auth.facebook['client_id'], redirect_uri=request.auth.facebook['redirect_uri'], scope=request.auth.facebook['permissions'] ) url = "https://%s%s?%s" % ( host, action, urllib.urlencode(params) ) return http.Http302(location=url) def facebook_end_auth(request): """ This is called by Facebook when the user has granted permission to the app. """ host = FACEBOOK_OAUTH['host'] action = FACEBOOK_OAUTH['access_token'] params = dict( client_id=request.auth.facebook['client_id'], redirect_uri=request.auth.facebook['redirect_uri'], client_secret=request.auth.facebook['client_secret'], code=request.query_params['code'][0] ) response = urllib.urlopen( "https://%s%s?%s" % (host, action, urllib.urlencode(params)) ).read() response = urlparse.parse_qs(response) access_token = response['access_token'][-1] action = FACEBOOK_OAUTH['profile'] profile = json.load(urllib.urlopen( "https://%s%s?%s" % (host, action, urllib.urlencode(dict(access_token=access_token))))) data = dict( access_token=access_token, permissions=request.auth.facebook['permissions'], uid=profile['id'], name=profile['name'] ) auth = FacebookAuthChannel(data) auth.complete_authentication(request.db, request.session) # Redirect somewhere useful return http.Http302(location=request.auth.facebook['complete_uri']) # Holds all the Facebook related authentication urls. facebook_router = controllers.Router( (r"^$", facebook_begin_auth), (r"^done/$", facebook_end_auth) )
{ "repo_name": "cargocult/rowan-python", "path": "rowan/auth/facebook.py", "copies": "1", "size": "3276", "license": "mit", "hash": -6779657904582992000, "line_mean": 29.0550458716, "line_max": 71, "alpha_frac": 0.6196581197, "autogenerated": false, "ratio": 3.881516587677725, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5001174707377725, "avg_score": null, "num_lines": null }
"""Authentication against the twitter OAUTH api.""" import urlparse import oauth2 as oauth import base import rowan.controllers as controllers import rowan.http as http TWITTER_OAUTH = { # These should be fine, unless twitter changes its API "host": "api.twitter.com", "callback": "http://localhost:8000/auth/twitter/done/", "request_token": dict(resource="/oauth/request_token", method="POST"), "user_authorization": dict(resource="/oauth/authorize", method="GET"), "access_token": dict(resource="/oauth/access_token", method="POST") } class TwitterOAuthError(Exception): pass class TwitterAuthChannel(base.AuthChannel): """ Encapsulates the handling of twitters authentication data and its storage in a database. """ def get_channel_key(self): return "twitter" def create_session_data(self): return { 'token': self.data['oauth_token'], 'secret': self.data['oauth_token_secret'], } def create_user_data(self): return { 'user_id': self.data['user_id'], 'user_name': self.data['screen_name'] } def create_auth_data(self): return { "twitter_id": self.data['user_id'] } def get_auth_data(self, db): auth_table_name = self.get_auth_table_name() return db[auth_table_name].find_one( {'twitter_id': self.data['user_id']} ) def twitter_begin_auth(request): """ Initiate the authentication against the twitter oauth server. """ consumer = oauth.Consumer( request.auth.twitter['consumer_key'], request.auth.twitter['consumer_secret'] ) client = oauth.Client(consumer) action = TWITTER_OAUTH['request_token'] host = TWITTER_OAUTH['host'] url = "http://%s%s" % (host, action['resource']) resp, content = client.request( url, action['method'], "oauth_callback=%s" % TWITTER_OAUTH['callback'] ) if resp['status'] != "200": raise TwitterOAuthError("Invalid response '%s'." % resp['status']) else: # Write the auth token to the session twitter_data = dict(urlparse.parse_qsl(content)) request.session['twitter'] = { "token": twitter_data['oauth_token'], "secret": twitter_data['oauth_token_secret'] } # Redirect the user to the twitter login screen action = TWITTER_OAUTH['user_authorization'] url = "http://%s%s?oauth_token=%s" % ( host, action['resource'], twitter_data['oauth_token'] ) return http.Http302(location=url) def twitter_end_auth(request): """This is called by Twitter when the user has granted permission to the app.""" # Create a temporary client based on the temporary token data. token = oauth.Token( request.session['twitter']['token'], request.session['twitter']['secret'] ) token.set_verifier(request.query_params['oauth_verifier']) consumer = oauth.Consumer( request.auth.twitter['consumer_key'], request.auth.twitter['consumer_secret'] ) client = oauth.Client(consumer, token) # Get the permanent token data from the above verifier. action = TWITTER_OAUTH['access_token'] host = TWITTER_OAUTH['host'] url = "http://%s%s" % (host, action['resource']) resp, content = client.request(url, action['method']) if resp['status'] != "200": raise TwitterOAuthError("Invalid response '%s'." % resp['status']) else: # Finish the authentication process. twitter_data = dict(urlparse.parse_qsl(content)) auth = TwitterAuthChannel(twitter_data) auth.complete_authentication(request.db, request.session) # Redirect somewhere useful return http.Http302(location=request.auth.twitter['complete_uri']) # Holds all the twitter related authentication urls. twitter_router = controllers.Router( (r"^$", twitter_begin_auth), (r"^done/$", twitter_end_auth) )
{ "repo_name": "cargocult/rowan-python", "path": "rowan/auth/twitter.py", "copies": "1", "size": "4049", "license": "mit", "hash": -7771066518132278000, "line_mean": 32.1885245902, "line_max": 74, "alpha_frac": 0.6238577427, "autogenerated": false, "ratio": 3.908301158301158, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5032158901001158, "avg_score": null, "num_lines": null }
"""Authentication and authorization policies, roles and permissions. Views are defined in the 'yait.views.auth' module, not here. """ from pyramid.security import authenticated_userid from sqlalchemy.orm.exc import NoResultFound from yait.models import DBSession from yait.models import Role from yait.models import User PERM_ADMIN_SITE = u'Administer site' PERM_MANAGE_PROJECT = u'Manage project' PERM_VIEW_PROJECT = u'View project' PERM_PARTICIPATE_IN_PROJECT = u'Participate in project' PERM_SEE_PRIVATE_TIMING_INFO = u'See private time information' ALL_PERMS = (PERM_ADMIN_SITE, PERM_MANAGE_PROJECT, PERM_VIEW_PROJECT, PERM_PARTICIPATE_IN_PROJECT, PERM_SEE_PRIVATE_TIMING_INFO) ROLE_SITE_ADMIN = u'Site administrator' ROLE_PROJECT_MANAGER = 1 ROLE_PROJECT_VIEWER = 2 ROLE_PROJECT_PARTICIPANT = 3 ROLE_PROJECT_INTERNAL_PARTICIPANT = 4 PERMISSIONS_FOR_ROLE = { ROLE_SITE_ADMIN: ALL_PERMS, ROLE_PROJECT_MANAGER: (PERM_MANAGE_PROJECT, PERM_SEE_PRIVATE_TIMING_INFO, PERM_PARTICIPATE_IN_PROJECT, PERM_VIEW_PROJECT), ROLE_PROJECT_INTERNAL_PARTICIPANT: (PERM_SEE_PRIVATE_TIMING_INFO, PERM_PARTICIPATE_IN_PROJECT, PERM_VIEW_PROJECT), ROLE_PROJECT_PARTICIPANT: (PERM_PARTICIPATE_IN_PROJECT, PERM_VIEW_PROJECT), ROLE_PROJECT_VIEWER: (PERM_VIEW_PROJECT, )} ROLE_LABELS = {ROLE_PROJECT_MANAGER: u'Project manager', ROLE_PROJECT_VIEWER: u'Viewer', ROLE_PROJECT_PARTICIPANT: u'Participant', ROLE_PROJECT_INTERNAL_PARTICIPANT: u'Internal participant'} class _AnonymousUser(object): def __init__(self): self.id = None self.is_admin = False def _get_user(request): """Return an instance of the ``User`` class if the user is logged in, or ``AnonymousUser`` otherwise. This function is never called explicitely by our code: it corresponds to the ``user`` reified property on requests (see ``app`` module where we call ``set_request_property()``). """ user = None user_id = authenticated_userid(request) if user_id: session = DBSession() try: user = session.query(User).filter_by(id=user_id).one() except NoResultFound: user = None if user is None: return _AnonymousUser() return user def check_password(login, password): """Return the corresponding user if the given credentials are correct. """ session = DBSession() try: user = session.query(User).filter_by(login=login).one() except NoResultFound: return None if not user.validate_password(password): return None return user class AuthorizationPolicy(object): pass # FIXME def has_permission(request, permission, context=None): """Return whether the current user is granted the given ``permission`` in this ``context``. Context must be a ``Project`` on which the permission is to be checked, or ``None`` if the permission is to be checked on the root level. In the latter case, only ``PERM_ADMIN_SITE`` may be checked (because other permissions do not make sense outside of projects). """ if permission not in ALL_PERMS: raise ValueError(u'Unknown permission: "%s"' % permission) if not context and permission != PERM_ADMIN_SITE: raise ValueError( u'Wrong permission on a site: "%s"' % permission) if context and permission == PERM_ADMIN_SITE: raise ValueError( u'Wrong permission on a project: "%s"' % permission) cache_key_admin = '_user_is_site_admin' if getattr(request, cache_key_admin, None): return True if context is None: cache_key = '_user_site_perms' else: cache_key = '_user_perms_%s' % context.name if getattr(request, cache_key, None) is not None: return permission in getattr(request, cache_key) # Shortcuts for public projects and anonymous users if context is not None and context.public and \ permission == PERM_VIEW_PROJECT: return True user_id = request.user.id if not user_id: return False session = DBSession() user_perms = () if request.user.is_admin: user_perms = PERMISSIONS_FOR_ROLE[ROLE_SITE_ADMIN] setattr(request, cache_key_admin, True) elif context is not None: try: row = session.query(Role).filter_by( user_id=user_id, project_id=context.id).one() except NoResultFound: pass else: user_perms = PERMISSIONS_FOR_ROLE[row.role] setattr(request, cache_key, user_perms) return permission in user_perms
{ "repo_name": "dbaty/Yait", "path": "yait/auth.py", "copies": "1", "size": "4844", "license": "bsd-3-clause", "hash": -352658436116404860, "line_mean": 32.8741258741, "line_max": 74, "alpha_frac": 0.64223782, "autogenerated": false, "ratio": 3.808176100628931, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4950413920628931, "avg_score": null, "num_lines": null }
import base64 import functools import logging import os import textwrap import httpx from airflow._vendor.connexion.utils import get_function_from_name import http.cookies from ..exceptions import (ConnexionException, OAuthProblem, OAuthResponseProblem, OAuthScopeProblem) logger = logging.getLogger('connexion.api.security') # use connection pool for OAuth tokeninfo limits = httpx.Limits(max_keepalive_connections=100, max_connections=100) session = httpx.Client(limits=limits) def get_tokeninfo_func(security_definition): """ :type security_definition: dict :rtype: function >>> get_tokeninfo_url({'x-tokenInfoFunc': 'foo.bar'}) '<function foo.bar>' """ token_info_func = (security_definition.get("x-tokenInfoFunc") or os.environ.get('TOKENINFO_FUNC')) if token_info_func: return get_function_from_name(token_info_func) token_info_url = (security_definition.get('x-tokenInfoUrl') or os.environ.get('TOKENINFO_URL')) if token_info_url: return functools.partial(get_tokeninfo_remote, token_info_url) return None def get_scope_validate_func(security_definition): """ :type security_definition: dict :rtype: function >>> get_scope_validate_func({'x-scopeValidateFunc': 'foo.bar'}) '<function foo.bar>' """ func = (security_definition.get("x-scopeValidateFunc") or os.environ.get('SCOPEVALIDATE_FUNC')) if func: return get_function_from_name(func) return validate_scope def get_basicinfo_func(security_definition): """ :type security_definition: dict :rtype: function >>> get_basicinfo_func({'x-basicInfoFunc': 'foo.bar'}) '<function foo.bar>' """ func = (security_definition.get("x-basicInfoFunc") or os.environ.get('BASICINFO_FUNC')) if func: return get_function_from_name(func) return None def get_apikeyinfo_func(security_definition): """ :type security_definition: dict :rtype: function >>> get_apikeyinfo_func({'x-apikeyInfoFunc': 'foo.bar'}) '<function foo.bar>' """ func = (security_definition.get("x-apikeyInfoFunc") or os.environ.get('APIKEYINFO_FUNC')) if func: return get_function_from_name(func) return None def get_bearerinfo_func(security_definition): """ :type security_definition: dict :rtype: function >>> get_bearerinfo_func({'x-bearerInfoFunc': 'foo.bar'}) '<function foo.bar>' """ func = (security_definition.get("x-bearerInfoFunc") or os.environ.get('BEARERINFO_FUNC')) if func: return get_function_from_name(func) return None def security_passthrough(function): """ :type function: types.FunctionType :rtype: types.FunctionType """ return function def security_deny(function): """ :type function: types.FunctionType :rtype: types.FunctionType """ def deny(*args, **kwargs): raise ConnexionException("Error in security definitions") return deny def get_authorization_info(auth_funcs, request, required_scopes): for func in auth_funcs: token_info = func(request, required_scopes) if token_info is not None: return token_info logger.info("... No auth provided. Aborting with 401.") raise OAuthProblem(description='No authorization token provided') def validate_scope(required_scopes, token_scopes): """ :param required_scopes: Scopes required to access operation :param token_scopes: Scopes granted by authorization server :rtype: bool """ required_scopes = set(required_scopes) if isinstance(token_scopes, list): token_scopes = set(token_scopes) else: token_scopes = set(token_scopes.split()) logger.debug("... Scopes required: %s", required_scopes) logger.debug("... Token scopes: %s", token_scopes) if not required_scopes <= token_scopes: logger.info(textwrap.dedent(""" ... Token scopes (%s) do not match the scopes necessary to call endpoint (%s). Aborting with 403.""").replace('\n', ''), token_scopes, required_scopes) return False return True def verify_authorization_token(request, token_info_func): """ :param request: ConnexionRequest :param token_info_func: types.FunctionType :rtype: dict """ authorization = request.headers.get('Authorization') if not authorization: return None try: auth_type, token = authorization.split(None, 1) except ValueError: raise OAuthProblem(description='Invalid authorization header') if auth_type.lower() != 'bearer': return None token_info = token_info_func(token) if token_info is None: raise OAuthResponseProblem( description='Provided token is not valid', token_response=None ) return token_info def verify_oauth(token_info_func, scope_validate_func): def wrapper(request, required_scopes): token_info = verify_authorization_token(request, token_info_func) if token_info is None: return None # Fallback to 'scopes' for backward compability token_scopes = token_info.get('scope', token_info.get('scopes', '')) if not scope_validate_func(required_scopes, token_scopes): raise OAuthScopeProblem( description='Provided token doesn\'t have the required scope', required_scopes=required_scopes, token_scopes=token_scopes ) return token_info return wrapper def verify_basic(basic_info_func): def wrapper(request, required_scopes): authorization = request.headers.get('Authorization') if not authorization: return None try: auth_type, user_pass = authorization.split(None, 1) except ValueError: raise OAuthProblem(description='Invalid authorization header') if auth_type.lower() != 'basic': return None try: username, password = base64.b64decode(user_pass).decode('latin1').split(':', 1) except Exception: raise OAuthProblem(description='Invalid authorization header') token_info = basic_info_func(username, password, required_scopes=required_scopes) if token_info is None: raise OAuthResponseProblem( description='Provided authorization is not valid', token_response=None ) return token_info return wrapper def get_cookie_value(cookies, name): ''' Returns cookie value by its name. None if no such value. :param cookies: str: cookies raw data :param name: str: cookies key ''' cookie_parser = http.cookies.SimpleCookie() cookie_parser.load(str(cookies)) try: return cookie_parser[name].value except KeyError: return None def verify_apikey(apikey_info_func, loc, name): def wrapper(request, required_scopes): def _immutable_pop(_dict, key): """ Pops the key from an immutable dict and returns the value that was popped, and a new immutable dict without the popped key. """ cls = type(_dict) try: _dict = _dict.to_dict(flat=False) return _dict.pop(key)[0], cls(_dict) except AttributeError: _dict = dict(_dict.items()) return _dict.pop(key), cls(_dict) if loc == 'query': try: apikey, request.query = _immutable_pop(request.query, name) except KeyError: apikey = None elif loc == 'header': apikey = request.headers.get(name) elif loc == 'cookie': cookieslist = request.headers.get('Cookie') apikey = get_cookie_value(cookieslist, name) else: return None if apikey is None: return None token_info = apikey_info_func(apikey, required_scopes=required_scopes) if token_info is None: raise OAuthResponseProblem( description='Provided apikey is not valid', token_response=None ) return token_info return wrapper def verify_bearer(bearer_info_func): """ :param bearer_info_func: types.FunctionType :rtype: types.FunctionType """ def wrapper(request, required_scopes): return verify_authorization_token(request, bearer_info_func) return wrapper def verify_none(): """ :rtype: types.FunctionType """ def wrapper(request, required_scopes): return {} return wrapper def verify_security(auth_funcs, required_scopes, function): @functools.wraps(function) def wrapper(request): token_info = get_authorization_info(auth_funcs, request, required_scopes) # Fallback to 'uid' for backward compability request.context['user'] = token_info.get('sub', token_info.get('uid')) request.context['token_info'] = token_info return function(request) return wrapper def get_tokeninfo_remote(token_info_url, token): """ Retrieve oauth token_info remotely using HTTP :param token_info_url: Url to get information about the token :type token_info_url: str :param token: oauth token from authorization header :type token: str :rtype: dict """ token_request = httpx.get(token_info_url, headers={'Authorization': 'Bearer {}'.format(token)}, timeout=5) if not token_request.ok: return None return token_request.json()
{ "repo_name": "nathanielvarona/airflow", "path": "airflow/_vendor/connexion/decorators/security.py", "copies": "3", "size": "9853", "license": "apache-2.0", "hash": 3671244064150476000, "line_mean": 27.8944281525, "line_max": 110, "alpha_frac": 0.6289454988, "autogenerated": false, "ratio": 4.1416561580496, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.62706016568496, "avg_score": null, "num_lines": null }
import functools import logging import os import textwrap import requests from ..exceptions import OAuthProblem, OAuthResponseProblem, OAuthScopeProblem logger = logging.getLogger('connexion.api.security') # use connection pool for OAuth tokeninfo adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) session = requests.Session() session.mount('http://', adapter) session.mount('https://', adapter) def get_tokeninfo_url(security_definition): ''' :type security_definition: dict :rtype: str >>> get_tokeninfo_url({'x-tokenInfoUrl': 'foo'}) 'foo' ''' token_info_url = (security_definition.get('x-tokenInfoUrl') or os.environ.get('TOKENINFO_URL')) return token_info_url def security_passthrough(function): """ :type function: types.FunctionType :rtype: types.FunctionType """ return function def verify_oauth(token_info_url, allowed_scopes, function): """ Decorator to verify oauth :param token_info_url: Url to get information about the token :type token_info_url: str :param allowed_scopes: Set with scopes that are allowed to access the endpoint :type allowed_scopes: set :type function: types.FunctionType :rtype: types.FunctionType """ @functools.wraps(function) def wrapper(request): logger.debug("%s Oauth verification...", request.url) authorization = request.headers.get('Authorization') # type: str if not authorization: logger.info("... No auth provided. Aborting with 401.") raise OAuthProblem(description='No authorization token provided') else: try: _, token = authorization.split() # type: str, str except ValueError: raise OAuthProblem(description='Invalid authorization header') logger.debug("... Getting token from %s", token_info_url) token_request = session.get(token_info_url, params={'access_token': token}, timeout=5) logger.debug("... Token info (%d): %s", token_request.status_code, token_request.text) if not token_request.ok: raise OAuthResponseProblem( description='Provided oauth token is not valid', token_response=token_request ) token_info = token_request.json() # type: dict if isinstance(token_info['scope'], list): user_scopes = set(token_info['scope']) else: user_scopes = set(token_info['scope'].split()) logger.debug("... Scopes required: %s", allowed_scopes) logger.debug("... User scopes: %s", user_scopes) if not allowed_scopes <= user_scopes: logger.info(textwrap.dedent(""" ... User scopes (%s) do not match the scopes necessary to call endpoint (%s). Aborting with 403.""").replace('\n', ''), user_scopes, allowed_scopes) raise OAuthScopeProblem( description='Provided token doesn\'t have the required scope', required_scopes=allowed_scopes, token_scopes=user_scopes ) logger.info("... Token authenticated.") request.context['user'] = token_info.get('uid') request.context['token_info'] = token_info return function(request) return wrapper
{ "repo_name": "NeostreamTechnology/Microservices", "path": "venv/lib/python2.7/site-packages/connexion/decorators/security.py", "copies": "1", "size": "3575", "license": "mit", "hash": 7714007610579205000, "line_mean": 36.6315789474, "line_max": 105, "alpha_frac": 0.6072727273, "autogenerated": false, "ratio": 4.508196721311475, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5615469448611475, "avg_score": null, "num_lines": null }
"""Authentication and Authorization tests against DC/OS Enterprise and root Marathon.""" import pytest import requests from shakedown.clients import dcos_url_path, marathon from shakedown.clients.authentication import DCOSAcsAuth from shakedown.clients.rpcclient import verify_ssl from shakedown.dcos.cluster import ee_version # NOQA F401 from shakedown.dcos.security import dcos_user, new_dcos_user @pytest.mark.skipif("ee_version() is None") def test_non_authenticated_user(): response = requests.get(dcos_url_path('service/marathon/v2/apps'), auth=None, verify=verify_ssl()) assert response.status_code == 401 @pytest.mark.skipif("ee_version() is None") def test_non_authorized_user(): with new_dcos_user('kenny', 'kenny') as auth_token: auth = DCOSAcsAuth(auth_token) response = requests.get(dcos_url_path('service/marathon/v2/apps'), auth=auth, verify=verify_ssl()) assert response.status_code == 403 # NOTE: this is a common test file. All test suites which import this common # set of tests will need to `from fixtures import user_billy` for this fixture to work. @pytest.mark.skipif("ee_version() is None") def test_authorized_non_super_user(user_billy): with dcos_user('billy', 'billy') as auth_token: client = marathon.create_client(auth_token=auth_token) assert len(client.get_apps()) == 0
{ "repo_name": "gsantovena/marathon", "path": "tests/system/marathon_auth_common_tests.py", "copies": "2", "size": "1366", "license": "apache-2.0", "hash": 5957815807943802000, "line_mean": 40.3939393939, "line_max": 106, "alpha_frac": 0.7349926794, "autogenerated": false, "ratio": 3.32360097323601, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0017847122117200605, "num_lines": 33 }
"""Authentication api""" from importlib import import_module from django.conf import settings from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY from django.db import IntegrityError from profiles.utils import is_duplicate_username_error from profiles.api import find_available_username USERNAME_COLLISION_ATTEMPTS = 10 def create_user_session(user): """ Creates a new session for the user based on the configured session engine Args: user(User): the user for which to create a session Returns: SessionBase: the created session """ SessionStore = import_module(settings.SESSION_ENGINE).SessionStore session = SessionStore() session[SESSION_KEY] = user._meta.pk.value_to_string(user) session[BACKEND_SESSION_KEY] = "django.contrib.auth.backends.ModelBackend" session[HASH_SESSION_KEY] = user.get_session_auth_hash() session.save() return session def create_user_with_generated_username(serializer, initial_username): """ Creates a User with a given username, and if there is a User that already has that username, finds an available username and reattempts the User creation. Args: serializer (UserSerializer instance): A user serializer instance that has been instantiated with user data and has passed initial validation initial_username (str): The initial username to attempt to save the User with Returns: User or None: The created User (or None if the User could not be created in the number of retries allowed) """ created_user = None username = initial_username attempts = 0 while created_user is None and attempts < USERNAME_COLLISION_ATTEMPTS: try: created_user = serializer.save(username=username) except IntegrityError as exc: if not is_duplicate_username_error(exc): raise username = find_available_username(initial_username) finally: attempts += 1 return created_user
{ "repo_name": "mitodl/bootcamp-ecommerce", "path": "authentication/api.py", "copies": "1", "size": "2069", "license": "bsd-3-clause", "hash": -2108860854990844000, "line_mean": 32.3709677419, "line_max": 99, "alpha_frac": 0.700821653, "autogenerated": false, "ratio": 4.420940170940171, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5621761823940171, "avg_score": null, "num_lines": null }
"""Authentication api""" import logging from django.contrib.auth import get_user_model from django.db import transaction, IntegrityError from social_core.utils import get_strategy from authentication.backends.micromasters import MicroMastersAuth from channels import api as channels_api from notifications import api as notifications_api from profiles import api as profile_api from course_catalog.tasks import update_enrollments_for_email User = get_user_model() log = logging.getLogger() def create_user(username, email, profile_data=None, user_extra=None): """ Ensures the user exists Args: email (str): the user's email profile (dic): the profile data for the user Returns: User: the user """ defaults = {} if user_extra is not None: defaults.update(user_extra) # this takes priority over a passed in value defaults.update({"username": username}) with transaction.atomic(): user, _ = User.objects.get_or_create(email=email, defaults=defaults) profile_api.ensure_profile(user, profile_data=profile_data) notifications_api.ensure_notification_settings( user, skip_moderator_setting=True ) # this could fail if the reddit backend is down # so if it fails we want to rollback this entire transaction channels_api.get_or_create_auth_tokens(user) update_enrollments_for_email.delay(user.email) return user def create_or_update_micromasters_social_auth(user, uid, details): """ Creates or updates MicroMasters social auth for a user Args: user (User): user to create the auth for uid (str): the micromasters username of the user details (dict): additional details Returns: UserSocialAuth: the created social auth record """ # avoid a circular import from social_django.utils import STORAGE, STRATEGY, load_backend strategy = get_strategy(STRATEGY, STORAGE) storage = strategy.storage backend = load_backend(strategy, MicroMastersAuth.name, None) try: social = storage.user.create_social_auth(user, uid, MicroMastersAuth.name) except IntegrityError: # if the user already has a social auth for MM, we don't want to fail # so just use the existing one social = ( storage.user.get_social_auth_for_user(user, provider=MicroMastersAuth.name) .filter(uid=uid) .first() ) # update metadata extra_data = backend.extra_data(user, uid, {"username": uid}, details) social.set_extra_data(extra_data) return social
{ "repo_name": "mitodl/open-discussions", "path": "authentication/api.py", "copies": "1", "size": "2640", "license": "bsd-3-clause", "hash": -7505764960439991000, "line_mean": 29.3448275862, "line_max": 87, "alpha_frac": 0.684469697, "autogenerated": false, "ratio": 4.0121580547112465, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5196627751711247, "avg_score": null, "num_lines": null }
""" Authentication Backend for CommCaer HQ """ from django.conf import settings from django.contrib.auth.models import User class HQBackend: """ Authenticate against a user's unsalted_password (given username and sha1 of username:password) """ def authenticate(self, username=None, password=None): # CZUE TODO: need to fix this raise NotImplementedError("Sorry this broke in the migration and needs to be fixed!") try: user = User.objects.get(username=username) if user.unsalted_password == password: return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_username_password(request): """ Checks whether a request comes from an authorized user. """ try: if not request.META.has_key('HTTP_AUTHORIZATION'): return (None, None) (authmeth, auth) = request.META['HTTP_AUTHORIZATION'].split(" ", 1) if authmeth.lower() != 'hq': return (None, None) # Extract auth parameters from request amap = get_auth_dict(auth) except Exception, e: # catch all errors (most likely poorly formatted POST's) # so we do not fail hard in the auth middleware return (None, None) try: username = amap['username'] password = amap['password'] except: return (None, None) return ( username, password ) def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap = {} for itm in auth_string.split(", "): (k, v) = [s.strip() for s in itm.split("=", 1)] amap[k] = v.replace('"', '') return amap
{ "repo_name": "commtrack/commtrack-core", "path": "apps/hq/authentication.py", "copies": "3", "size": "2135", "license": "bsd-3-clause", "hash": 8706163287827843000, "line_mean": 30.8805970149, "line_max": 93, "alpha_frac": 0.5817330211, "autogenerated": false, "ratio": 3.9174311926605503, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.010354939939478908, "num_lines": 67 }
""" Authentication Backend for CommCaer HQ """ from django.conf import settings from hq.models import ExtUser class HQBackend: """ Authenticate against extuser.unsalted_password (given username and sha1 of username:password) """ def authenticate(self, username=None, password=None): try: user = ExtUser.objects.get(username=username) if user.unsalted_password == password: return user else: return None except ExtUser.DoesNotExist: return None def get_user(self, user_id): try: return ExtUser.objects.get(pk=user_id) except ExtUser.DoesNotExist: return None def get_username_password(request): """ Checks whether a request comes from an authorized user. """ try: if not request.META.has_key('HTTP_AUTHORIZATION'): return (None, None) (authmeth, auth) = request.META['HTTP_AUTHORIZATION'].split(" ", 1) if authmeth.lower() != 'hq': return (None, None) # Extract auth parameters from request amap = get_auth_dict(auth) except Exception, e: # catch all errors (most likely poorly formatted POST's) # so we do not fail hard in the auth middleware return (None, None) try: username = amap['username'] password = amap['password'] except: return (None, None) return ( username, password ) def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap = {} for itm in auth_string.split(", "): (k, v) = [s.strip() for s in itm.split("=", 1)] amap[k] = v.replace('"', '') return amap
{ "repo_name": "commtrack/commtrack-old-to-del", "path": "apps/hq/authentication.py", "copies": "1", "size": "1998", "license": "bsd-3-clause", "hash": -2905620576605606000, "line_mean": 29.7538461538, "line_max": 75, "alpha_frac": 0.5770770771, "autogenerated": false, "ratio": 3.8497109826589595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4926788059758959, "avg_score": null, "num_lines": null }
""" Authentication Backend for CommCaer HQ """ from django.conf import settings from django.contrib.auth.models import User class HQBackend: """ Authenticate against a user's unsalted_password (given username and sha1 of username:password) """ def authenticate(self, username=None, password=None): # CZUE TODO: need to fix this raise NotImplementedError("Sorry this broke in the migration and needs to be fixed!") try: user = User.objects.get(username=username) if user.unsalted_password == password: return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_username_password(request): """ Checks whether a request comes from an authorized user. """ try: if not request.META.has_key('HTTP_AUTHORIZATION'): return (None, None) (authmeth, auth) = request.META['HTTP_AUTHORIZATION'].split(" ", 1) if authmeth.lower() != 'hq': return (None, None) # Extract auth parameters from request amap = get_auth_dict(auth) except Exception, e: # catch all errors (most likely poorly formatted POST's) # so we do not fail hard in the auth middleware return (None, None) try: username = amap['username'] password = amap['password'] except: return (None, None) return ( username, password ) def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap = {} for itm in auth_string.split(", "): (k, v) = [s.strip() for s in itm.split("=", 1)] amap[k] = v.replace('"', '') return amap
{ "repo_name": "commtrack/temp-aquatest", "path": "apps/hq/authentication.py", "copies": "1", "size": "2201", "license": "bsd-3-clause", "hash": -8073375033640239000, "line_mean": 30.8805970149, "line_max": 93, "alpha_frac": 0.5642889596, "autogenerated": false, "ratio": 3.9945553539019962, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5058844313501996, "avg_score": null, "num_lines": null }
""" Authentication backend. Please use slugify function to get username from email """ from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend from tastypie.authentication import ApiKeyAuthentication class EmailAuthBackend(ModelBackend): """ Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair. """ def authenticate(self, username=None, password=None): """ Authenticate a user based on email address as the user name. """ try: user = User.objects.get(email=username) if user.check_password(password): return user except User.DoesNotExist: return None def supports_inactive_user(self): return False class EmailApiKeyAuthentication (ApiKeyAuthentication): """ The same as base class, but use email to find user """ def is_authenticated(self, request, **kwargs): email = request.GET.get('username') or request.POST.get('username') api_key = request.GET.get('api_key') or request.POST.get('api_key') if not email or not api_key: return self._unauthorized() try: user = User.objects.get(email=email) except (User.DoesNotExist, User.MultipleObjectsReturned): return self._unauthorized() request.user = user return self.get_key(user, api_key)
{ "repo_name": "iutinvg/django-email-auth-backend", "path": "backends.py", "copies": "1", "size": "1471", "license": "mit", "hash": -6987307988962641000, "line_mean": 30.9782608696, "line_max": 86, "alpha_frac": 0.6634942216, "autogenerated": false, "ratio": 4.444108761329305, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0002498750624687656, "num_lines": 46 }
"""Authentication backend registry.""" from __future__ import unicode_literals import logging from warnings import warn from django.conf import settings from django.contrib.auth import get_backends from django.utils.translation import ugettext_lazy as _ from djblets.registries.registry import (ALREADY_REGISTERED, LOAD_ENTRY_POINT, NOT_REGISTERED, UNREGISTER) from reviewboard.accounts.backends.base import BaseAuthBackend from reviewboard.accounts.backends.standard import StandardAuthBackend from reviewboard.registries.registry import EntryPointRegistry _enabled_auth_backends = [] _auth_backend_setting = None class AuthBackendRegistry(EntryPointRegistry): """A registry for managing authentication backends.""" entry_point = 'reviewboard.auth_backends' lookup_attrs = ('backend_id',) errors = { ALREADY_REGISTERED: _( '"%(item)r" is already a registered authentication backend.' ), LOAD_ENTRY_POINT: _( 'Error loading authentication backend %(entry_point)s: %(error)s' ), NOT_REGISTERED: _( 'No authentication backend registered with %(attr_name)s = ' '%(attr_value)s.' ), UNREGISTER: _( '"%(item)r is not a registered authentication backend.' ), } def process_value_from_entry_point(self, entry_point): """Load the class from the entry point. If the class lacks a value for :py:attr:`~reviewboard.accounts.backends.base.BaseAuthBackend .backend_id`, it will be set as the entry point's name. Args: entry_point (pkg_resources.EntryPoint): The entry point. Returns: type: The :py:class:`~reviewboard.accounts.backends.base.BaseAuthBackend` subclass. """ cls = entry_point.load() if not cls.backend_id: logging.warning('The authentication backend %r did not provide ' 'a backend_id attribute. Setting it to the ' 'entry point name ("%s")', cls, entry_point.name) cls.backend_id = entry_point.name return cls def get_defaults(self): """Yield the authentication backends. This will make sure the standard authentication backend is always registered and returned first. Yields: type: The :py:class:`~reviewboard.accounts.backends.base.BaseAuthBackend` subclasses. """ yield StandardAuthBackend for value in super(AuthBackendRegistry, self).get_defaults(): yield value def unregister(self, backend_class): """Unregister the requested authentication backend. Args: backend_class (type): The class of the backend to unregister. This must be a subclass of :py:class:`~reviewboard.accounts.backends.base .BaseAuthBackend`. Raises: djblets.registries.errors.ItemLookupError: Raised when the class cannot be found. """ self.populate() try: super(AuthBackendRegistry, self).unregister(backend_class) except self.lookup_error_class as e: logging.error('Failed to unregister unknown authentication ' 'backend "%s".', backend_class.backend_id) raise e def get_auth_backend(self, auth_backend_id): """Return the requested authentication backend, if it exists. Args: auth_backend_id (unicode): The unique ID of the :py:class:`~reviewboard.accounts.backends.base.BaseAuthBackend` class. Returns: type: The :py:class:`~reviewboard.accounts.backends.base.BaseAuthBackend` subclass, or ``None`` if it is not registered. """ return self.get('backend_id', auth_backend_id) def get_enabled_auth_backends(): """Return all authentication backends being used by Review Board. The returned list contains every authentication backend that Review Board will try, in order. Returns: list of type: The list of registered :py:class:`~reviewboard.accounts.backends.base.BaseAuthBackend` subclasses. """ global _enabled_auth_backends global _auth_backend_setting if (not _enabled_auth_backends or _auth_backend_setting != settings.AUTHENTICATION_BACKENDS): _enabled_auth_backends = list(get_backends()) _auth_backend_setting = settings.AUTHENTICATION_BACKENDS return _enabled_auth_backends #: Registry instance for working with available authentication backends. auth_backends = AuthBackendRegistry()
{ "repo_name": "reviewboard/reviewboard", "path": "reviewboard/accounts/backends/registry.py", "copies": "2", "size": "4924", "license": "mit", "hash": 298989174236463200, "line_mean": 30.974025974, "line_max": 79, "alpha_frac": 0.6169780666, "autogenerated": false, "ratio": 4.689523809523809, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6306501876123809, "avg_score": null, "num_lines": null }
"""Authentication backends for Connect""" # pylint: disable=protected-access from django.core.cache import cache from django.contrib.auth.backends import ModelBackend class CachedModelAuthBackend(ModelBackend): """An extension of `ModelBackend` that allows caching""" def get_all_permissions(self, user_obj, obj=None): """Return all permissions for a user""" # Anonymous users should have no permissions by default if user_obj.is_anonymous() or obj is not None: return set() # This should still work even if django removes `user._perm_cache` from # future releases of the auth `ModelBackend` if not hasattr(user_obj, '_perm_cache'): key = '{userkey}_permissions'.format(userkey=user_obj.cache_key) cache_result = cache.get(key) if cache_result is None: user_obj._perm_cache = super( CachedModelAuthBackend, self).get_all_permissions( user_obj, obj) # Cache permissions for 15 minutes. As adding a user to a group # will result in a change of the modified_at column and thus # the `cache_key` we don't have to hugely worry about changes cache.set(key, user_obj._perm_cache, 60*30) else: user_obj._perm_cache = cache_result return user_obj._perm_cache
{ "repo_name": "ofa/connect", "path": "open_connect/connect_core/utils/auth_backends.py", "copies": "2", "size": "1417", "license": "mit", "hash": 7225496955672206000, "line_mean": 46.2333333333, "line_max": 79, "alpha_frac": 0.6217360621, "autogenerated": false, "ratio": 4.333333333333333, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 30 }
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'lazysignup.backends.LazySignupBackend', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'lazysignup', 'antisocial', 'asn', ) # Django settings for asn project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'asn.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '4x*fa1t-6#n9k0779s_1v%ml72eop9(dx1#g&amp;t4krr66^yas7-' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'asn.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'asn.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
{ "repo_name": "danfairs/antisocial-network", "path": "asn/settings.py", "copies": "1", "size": "5790", "license": "mit", "hash": 3937444925355757600, "line_mean": 33.0588235294, "line_max": 108, "alpha_frac": 0.6856649396, "autogenerated": false, "ratio": 3.7163029525032094, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49019678921032095, "avg_score": null, "num_lines": null }
# [ Authentication Backends ] # import logging import os CLEAR_TEXT=1 MD5_HASH =2 OTHER =3 class AbstractBackend(): passwordStorage = CLEAR_TEXT # specifies if the passwords are kept in clear text def passHash(self, username, password, realm): return password; def load(self): pass def check(self, username, password, realm): """ Checks if there is a user with the specified username and password for the specified realm @param string username @param string password in clear text @return boolean """ return self.get(username) == self.passHash(username, password, realm) def has_key(self, key): pass def get(self, key, defaultValue=None): try: return self._get(key) except KeyError: return defaultValue def __getitem__(self, key): if isinstance(key, slice): raise ValueError("The key cannot be slice") return self._get(key) def _get(self, key): raise Exception("Implement this method in the child class") class FileBackend(AbstractBackend): data = {} modified = None def __init__(self, file, delimiter=":"): self.file = file self.delimiter = delimiter self.data = {} def load(self): stats = os.stat(self.file) if stats.st_mtime == self.modified: return logging.getLogger().debug("Loading auth data") self.modified = stats.st_mtime f = open(self.file) lines = f.readlines() f.close() for line in lines: try: (user,password) = line.rstrip().split(self.delimiter,2) self.data[user] = password except ValueError: # got invalid line continue def has_key(self, key): return self.data.has_key(key) def _get(self, key): return self.data[key] import hashlib class Md5FileBackend(FileBackend): passwordStorage=MD5_HASH """ File Backend where the passwords are stored as MD5 hash from username, realm and password """ def passHash(self, username, password, realm): return hashlib.md5('%s:%s:%s' % (username, realm, password)).hexdigest(); from core.pattern import Decorator import core.pool.Redis as Redis class CacheDecorator(Decorator): connectionWrapper = None def __init__(self, obj, expiration=3600, prefix="auth_"): Decorator.__init__(self, obj) object.__setattr__(self, "connectionWrapper", None) object.__setattr__(self, "prefix", prefix) object.__setattr__(self, "expiration", expiration) def check(self, username, password, realm): key = hashlib.md5("%s-%s-%s" % (username, password, realm)).hexdigest() cacheKey = self.getCacheKey(key) redis = self._getClient() value = redis.get(cacheKey) if value: return True value = self._obj.check(username, password, realm) if value: redis.set(cacheKey, value) redis.expire(cacheKey, self.expiration) return value def has_key(self, key): cacheKey = self.getCacheKey(key) redis = self._getClient() value = redis.get(cacheKey) if value: return True value = self._obj._get(key) if value: redis.set(cacheKey, value) redis.expire(cacheKey, self.expiration) return value def get(self, key, defaultValue=None): try: return self._get(key) except KeyError: return defaultValue def __getitem__(self, key): if isinstance(key, slice): raise ValueError("The key cannot be slice") return self._get(key) def _get(self, key): cacheKey = self.getCacheKey(key) redis = self._getClient() value = redis.get(cacheKey) if value: return value value = self._obj._get(key) if value: redis.set(cacheKey, value) redis.expire(cacheKey, self.expiration) return value def delKey(self, key): redis.delete(self.getCacheKey(key)) def getCacheKey(self, key): return self.prefix + key def _getClient(self): if not self.connectionWrapper: object.__setattr__(self, "connectionWrapper", Redis.ConnectionPool().get()) return self.connectionWrapper.getConnection() def __del__(self): # delete object references manually if self.connectionWrapper is not None: object.__delattr__(self, 'connectionWrapper') Decorator.__del__(self)
{ "repo_name": "slaff/attachix", "path": "server/core/provider/authentications/backend.py", "copies": "1", "size": "4729", "license": "mit", "hash": 6532260040631296000, "line_mean": 26.8235294118, "line_max": 98, "alpha_frac": 0.5901882005, "autogenerated": false, "ratio": 4.256525652565257, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006218730208644457, "num_lines": 170 }
AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend', 'social.backends.twitter.TwitterOAuth', 'social.backends.github.GithubOAuth2', ) # OAuth2 ACCESS_TOKEN_EXPIRE_SECONDS = 60 * 60 * 24 * 365 # 1 year SOCIAL_AUTH_PROTECTED_USER_FIELDS = ['email'] # https://apps.twitter.com/ # this is DEV credentials, place production settings into the secure_settings.py SOCIAL_AUTH_TWITTER_KEY = 'zfUBhL9cF0B44r33AzszA' SOCIAL_AUTH_TWITTER_SECRET = 'v0rfjbdVUozKWjVSxQ0Wh5h0RKuZQy9CTIu35L9KLI' # https://github.com/settings/applications # this is DEV credentials, place production settings into the secure_settings.py SOCIAL_AUTH_GITHUB_KEY = '7349d3551b5d86c85be1' SOCIAL_AUTH_GITHUB_SECRET = '6606dc0b084d8e304c0fbd5c794f4901c2785198' LOGIN_REDIRECT_URL = '/after-login/' SOCIAL_AUTH_PIPELINE = ( # adds key 'details' with information about user, taken from a backend 'social.pipeline.social_auth.social_details', # adds key uid, taken from backend 'social.pipeline.social_auth.social_uid', # checks if authentication is allowed and trows exception AuthForbidden 'social.pipeline.social_auth.auth_allowed', # gets a social profile from db and checks if it is not associated with another user # populates 'social', 'user', 'is_new' and 'new_association' keys 'social.pipeline.social_auth.social_user', # chooses username for a new user and stores it in a 'username' key 'social.pipeline.user.get_username', # calls strategy's create_user if there isn't user yet # created user is stored in 'user' key, and 'is_new' key become True 'social.pipeline.user.create_user', # adds web/allmychanges package 'allmychanges.auth.pipeline.add_default_package', # associates social profile with current user 'social.pipeline.social_auth.associate_user', # loads extra data from the backend and stores it in a social profile 'social.pipeline.social_auth.load_extra_data', # updates user model with data from provider # sensitive fields could be protected using 'PROTECTED_USER_FIELDS' # settings # WARNING, these fields will be overwritten at each login 'social.pipeline.user.user_details', )
{ "repo_name": "AllMyChanges/allmychanges.com", "path": "allmychanges/settings/auth.py", "copies": "1", "size": "2237", "license": "bsd-2-clause", "hash": -6580981944081446000, "line_mean": 42.862745098, "line_max": 88, "alpha_frac": 0.7313366115, "autogenerated": false, "ratio": 3.420489296636086, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9639634392925929, "avg_score": 0.0024383030420315186, "num_lines": 51 }
AUTHENTICATION_BACKENDS = ( 'social_auth.backends.contrib.douban.Douban2Backend', 'social_auth.backends.contrib.qq.QQBackend', 'social_auth.backends.contrib.weibo.WeiboBackend', 'social_auth.backends.contrib.renren.RenRenBackend', 'social_auth.backends.contrib.baidu.BaiduBackend', 'social_auth.backends.contrib.weixin.WeixinBackend', 'social_oauth.backends.NickNameBackend', 'django.contrib.auth.backends.ModelBackend', ) TEMPLATE_CONTEXT_PROCESSORS += ( 'django.contrib.auth.context_processors.auth', 'social_auth.context_processors.social_auth_by_type_backends', 'social_auth.context_processors.social_auth_login_redirect', ) SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.partial.save_status_to_session', 'social.pipeline.social_auth.save_authentication_user_detail_to_session', ) SOCIAL_AUTH_DISCONNECT_PIPELINE = ( 'social.pipeline.disconnect.allowed_to_disconnect', 'social.pipeline.disconnect.get_entries', 'social.pipeline.disconnect.revoke_tokens', 'social.pipeline.disconnect.disconnect' ) SOCIAL_AUTH_LOGIN_URL = '/login-url' SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error' SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/logged-in' SOCIAL_AUTH_NEW_USER_REDIRECT_URL = '/new-users-redirect-url' SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/oauth/newassociation' SOCIAL_AUTH_BACKEND_ERROR_URL = '/new-error-url' SOCIAL_AUTH_AUTHENTICATION_SUCCESS_URL = '/oauth/authentication/success' SOCIAL_AUTH_WEIBO_KEY = '' SOCIAL_AUTH_WEIBO_SECRET = '' SOCIAL_AUTH_WEIBO_AUTH_EXTRA_ARGUMENTS = {'forcelogin': 'true'} SOCIAL_AUTH_WEIBO_FIELDS_STORED_IN_SESSION = ['auth过程中的附加参数'] SOCIAL_AUTH_QQ_KEY = '' SOCIAL_AUTH_QQ_SECRET = '' SOCIAL_AUTH_QQ_FIELDS_STORED_IN_SESSION = ['auth过程中的附加参数'] SOCIAL_AUTH_DOUBAN_OAUTH2_KEY = '' SOCIAL_AUTH_DOUBAN_OAUTH2_SECRET = '' SOCIAL_AUTH_RENREN_KEY = '' SOCIAL_AUTH_RENREN_SECRET = '' SOCIAL_AUTH_BAIDU_KEY = '' SOCIAL_AUTH_BAIDU_SECRET = '' SOCIAL_AUTH_WEIXIN_KEY = '' SOCIAL_AUTH_WEIXIN_SECRET = '' SOCIAL_AUTH_WEIXIN_SCOPE = ['snsapi_login',]
{ "repo_name": "duoduo369/social_auth_demo", "path": "snippet/settings.py", "copies": "2", "size": "2218", "license": "mit", "hash": 6229452574561048000, "line_mean": 33.15625, "line_max": 77, "alpha_frac": 0.7397072278, "autogenerated": false, "ratio": 2.8612565445026177, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.4600963772302618, "avg_score": null, "num_lines": null }
AUTHENTICATION_BACKENDS = ( 'social.backends.amazon.AmazonOAuth2', 'social.backends.angel.AngelOAuth2', 'social.backends.aol.AOLOpenId', 'social.backends.appsfuel.AppsfuelOAuth2', 'social.backends.behance.BehanceOAuth2', 'social.backends.belgiumeid.BelgiumEIDOpenId', 'social.backends.bitbucket.BitbucketOAuth', 'social.backends.box.BoxOAuth2', 'social.backends.clef.ClefOAuth2', 'social.backends.coinbase.CoinbaseOAuth2', 'social.backends.dailymotion.DailymotionOAuth2', 'social.backends.disqus.DisqusOAuth2', 'social.backends.douban.DoubanOAuth2', 'social.backends.dropbox.DropboxOAuth', 'social.backends.evernote.EvernoteSandboxOAuth', 'social.backends.facebook.FacebookAppOAuth2', 'social.backends.facebook.FacebookOAuth2', 'social.backends.fedora.FedoraOpenId', 'social.backends.fitbit.FitbitOAuth', 'social.backends.flickr.FlickrOAuth', 'social.backends.foursquare.FoursquareOAuth2', 'social.backends.github.GithubOAuth2', 'social.backends.google.GoogleOAuth', 'social.backends.google.GoogleOAuth2', 'social.backends.google.GoogleOpenId', 'social.backends.google.GooglePlusAuth', 'social.backends.instagram.InstagramOAuth2', 'social.backends.jawbone.JawboneOAuth2', 'social.backends.linkedin.LinkedinOAuth', 'social.backends.linkedin.LinkedinOAuth2', 'social.backends.live.LiveOAuth2', 'social.backends.livejournal.LiveJournalOpenId', 'social.backends.mailru.MailruOAuth2', 'social.backends.mendeley.MendeleyOAuth', 'social.backends.mendeley.MendeleyOAuth2', 'social.backends.mixcloud.MixcloudOAuth2', 'social.backends.odnoklassniki.OdnoklassnikiOAuth2', 'social.backends.open_id.OpenIdAuth', 'social.backends.openstreetmap.OpenStreetMapOAuth', 'social.backends.orkut.OrkutOAuth', 'social.backends.persona.PersonaAuth', 'social.backends.podio.PodioOAuth2', 'social.backends.rdio.RdioOAuth1', 'social.backends.rdio.RdioOAuth2', 'social.backends.readability.ReadabilityOAuth', 'social.backends.reddit.RedditOAuth2', 'social.backends.runkeeper.RunKeeperOAuth2', 'social.backends.skyrock.SkyrockOAuth', 'social.backends.soundcloud.SoundcloudOAuth2', 'social.backends.stackoverflow.StackoverflowOAuth2', 'social.backends.steam.SteamOpenId', 'social.backends.stocktwits.StocktwitsOAuth2', 'social.backends.stripe.StripeOAuth2', 'social.backends.suse.OpenSUSEOpenId', 'social.backends.thisismyjam.ThisIsMyJamOAuth1', 'social.backends.trello.TrelloOAuth', 'social.backends.tripit.TripItOAuth', 'social.backends.tumblr.TumblrOAuth', 'social.backends.twilio.TwilioAuth', 'social.backends.twitter.TwitterOAuth', 'social.backends.vk.VKOAuth2', 'social.backends.weibo.WeiboOAuth2', 'social.backends.xing.XingOAuth', 'social.backends.yahoo.YahooOAuth', 'social.backends.yahoo.YahooOpenId', 'social.backends.yammer.YammerOAuth2', 'social.backends.yandex.YandexOAuth2', 'social.backends.vimeo.VimeoOAuth1', 'social.backends.email.EmailAuth', 'social.backends.username.UsernameAuth', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/done/' SOCIAL_AUTH_STRATEGY = 'social.strategies.django_strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social.apps.django_app.default.models.DjangoStorage' SOCIAL_AUTH_GOOGLE_OAUTH_SCOPE = [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/userinfo.profile' ] # SOCIAL_AUTH_EMAIL_FORM_HTML = 'email_signup.html' # SOCIAL_AUTH_EMAIL_VALIDATION_FUNCTION = 'example.app.mail.send_validation' # SOCIAL_AUTH_EMAIL_VALIDATION_URL = '/email-sent/' # SOCIAL_AUTH_USERNAME_FORM_HTML = 'username_signup.html' SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'common.pipeline.require_email', 'social.pipeline.mail.mail_validation', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' )
{ "repo_name": "night-crawler/django-chant", "path": "chant_project/social_settings.py", "copies": "1", "size": "4310", "license": "mit", "hash": -5897750761871019000, "line_mean": 40.0476190476, "line_max": 76, "alpha_frac": 0.7473317865, "autogenerated": false, "ratio": 3.1691176470588234, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.44164494335588234, "avg_score": null, "num_lines": null }
# authentication class for API from flask import request from flask_restful import Resource, fields from .parsers import common_get_parser, common_post_parser from .base import ApiCommon from ..models import JobRefresh from ..decorators import token_required, json from ...server.utils import Permission from ...server.tasks.ecommerce import async_run_get_ecommercetask ################ #### view #### ################ job_fields = { 'id' : fields.Integer(), 'status' : fields.String(), 'start_datetime' : fields.String(), 'finish_datetime' : fields.String() } class JobApi(Resource): @token_required(common_post_parser, Permission.MODERATE_API) @json def post(self, *args, **kwargs): '''Create new JobRefresh via post api request''' payload = request.json['items'] or {} return_msg = ApiCommon.post_reference(payload, JobRefresh, job_fields, 'id') return return_msg, 200 class TaskApi(Resource): @token_required(common_get_parser, Permission.VIEW_API) @json def get(self, *args, **kwargs): '''Return Task Id via get api request''' customer_code = kwargs.pop('customer_code', '') if customer_code == 'ecommerce': async_run_get_ecommercetask() return 200 else: return 404
{ "repo_name": "slobodz/TeamServices", "path": "project/server/api/task.py", "copies": "1", "size": "1325", "license": "mit", "hash": 6647534116522931000, "line_mean": 29.8372093023, "line_max": 84, "alpha_frac": 0.641509434, "autogenerated": false, "ratio": 3.9201183431952664, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007909508667504329, "num_lines": 43 }
# authentication class for API from flask_restful import Resource from flask_apispec import MethodResource, doc from flask import abort from sqlalchemy.orm.exc import NoResultFound from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from .parsers import auth_post_parser from ...server.models import User from ...server.utils import Permission ################ #### view #### ################ @doc(description='authentication repository', tags=['auth']) class AuthApi(MethodResource): '''default auth class to handle rest API calls ''' def post(self): args = auth_post_parser.parse_args() try: user = User.query.filter_by(email=args['Username']).one() except NoResultFound: abort(404) except Exception: abort(500) if user: if user.verify_password(args['Password']): if user.can(Permission.VIEW_API): token = user.generate_confirmation_token() return {"token": token.decode('UTF-8')} else: abort(403) else: abort(401) else: abort(404)
{ "repo_name": "slobodz/TeamServices", "path": "project/server/api/auth.py", "copies": "1", "size": "1177", "license": "mit", "hash": 4223939049550708000, "line_mean": 30, "line_max": 70, "alpha_frac": 0.6032285472, "autogenerated": false, "ratio": 4.526923076923077, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5630151624123076, "avg_score": null, "num_lines": null }
"""Authentication exceptions""" from social_core.exceptions import AuthException class RequireProviderException(AuthException): """The user is required to authenticate via a specific provider/backend""" def __init__(self, backend, social_auth): """ Args: social_auth (social_django.models.UserSocialAuth): A social auth objects """ self.social_auth = social_auth super().__init__(backend) class PartialException(AuthException): """Partial pipeline exception""" def __init__( self, backend, partial, errors=None, reason_code=None, user=None ): # pylint:disable=too-many-arguments self.partial = partial self.errors = errors self.reason_code = reason_code self.user = user super().__init__(backend) class InvalidPasswordException(PartialException): """Provided password was invalid""" def __str__(self): return "Unable to login with that email and password combination" class RequireEmailException(PartialException): """Authentication requires an email""" def __str__(self): return "Email is required to login" class RequireRegistrationException(PartialException): """Authentication requires registration""" def __str__(self): return "There is no account with that email" class RequirePasswordException(PartialException): """Authentication requires a password""" def __str__(self): return "Password is required to login" class RequirePasswordAndPersonalInfoException(PartialException): """Authentication requires a password and address""" def __str__(self): return "Password and address need to be filled out" class RequireProfileException(PartialException): """Authentication requires a profile""" def __str__(self): return "Profile needs to be filled out" class UserCreationFailedException(PartialException): """Raised if user creation with a generated username failed""" class UserExportBlockedException(PartialException): """The user is blocked for export reasons from continuing to sign up""" class UserTryAgainLaterException(PartialException): """The user should try to register again later""" class UserMissingSocialAuthException(Exception): """Raised if the user doesn't have a social auth"""
{ "repo_name": "mitodl/bootcamp-ecommerce", "path": "authentication/exceptions.py", "copies": "1", "size": "2364", "license": "bsd-3-clause", "hash": 908950284583427500, "line_mean": 26.8117647059, "line_max": 84, "alpha_frac": 0.6958544839, "autogenerated": false, "ratio": 4.7565392354124745, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5952393719312475, "avg_score": null, "num_lines": null }
"""Authentication Extension User authentication hooks for WebCore applications. * This extension is **available in**: `web.security>=2.1.0,<2.2.0` * This extension has **no external package dependencies or language requirements**. * This extension is **available with the name** `auth`, 'authn', or 'authentication' in the `web.ext` namespace. * This extension adds the following **context attributes**: * `authenticate` * `deauthenticate` * This extension uses **namespaced plugins** from: * `web.auth.lookup` * `web.auth.authenticate` # Introduction This extension ## Operation This extension provides a method of performing modular user authentication. # Usage ## Enabling the Extension ### Imperative Configuration ```python from web.ext.acl import ACLExtension, when app = Application("Hi.", extensions=[AuthExtension(...)]) ``` ### Declarative Configuration Using a JSON or YAML-based configuration, you would define your application's `extensions` section either with the bare extension declared: ```yaml application: root: "Hi." extensions: authentication: ... ``` """ from functools import partialmethod from webob.exc import HTTPTemporaryRedirect from marrow.package.loader import load from ..core.compat import unicode, str from ..core.util import lazy log = __import__('logging').getLogger(__name__) class AuthExtension: """User authentication extension. """ provides = {'auth', 'authentication'} extensions = {'web.auth.lookup', 'web.auth.authenticate'} context = {'user'} def __init__(self, name='user', session='user', intercept={401}, handler='/authenticate', internal=True, lookup=None, authenticate=None): """Configure WebCore authentication. The `name` represents the name of the active user object within the context. The `session` argument represents the session attribute to use to store the active user ID after successful authentication. If defined, the set of HTTP status code integers to intercept and redirect to the `handler` are passed as `intercept`. If the application attempts to return a response matching one of those status codes, the user will instead be directed to the authentication handler URL. If `internal` is truthy that redirection will not be visible to the user, instead, returning the authentication page as the response body to the intercepted status integer. The guts of the machinery are the `lookup` and `authenticate` callbacks, which should either be references to callables within your code (or library code) or string dot-colon references to the same or a plugin name. Reference the module documentation for callback examples. The `name` provided may be `None`, indicating pure access to the logged in user's identity through the session. """ super().__init__() # Authentication data storage configuration. self._name = name self._session = session # HTTP status code interception and redirection configuration. self._intercept = set(intercept) if intercept else None self._handler = handler self._internal = internal # Authentication callback references. self._lookup = lookup self._authenticate = authenticate if intercept: self.after = self._intercept log.info("Authentication extension prepared.") # Application-Level Callbacks def start(self, context): """Called to load the authentication callbacks and attach them to the context, with glue.""" if isinstance(self._lookup, (str, unicode)): self._lookup = load(self._lookup, 'web.auth.lookup') if isinstance(self._authenticate, (str, unicode)): self._authenticate = load(self._authenticate, 'web.auth.authenticate') if self._name: context[self._name] = None # TODO: context.user = lazy(...) context.authenticate = lazy(partialmethod(partialmethod, self.authenticate), 'authenticate') context.deauthenticate = lazy(partialmethod(partialmethod, self.deauthenticate), 'deauthenticate') # Request-Level Callbacks def _intercept(self, context): """Called after dispatch has returned and the response populated, to intercept and redirect. Optionally assigned to the correct callback name (`after`) only if interception is enabled. """ if context.response.status_int not in self._intercept: return # Exit early if our condition is not met. if not self._internal: context.response = HTTPTemporaryRedirect(location=self._handler) return # External redirects are easy. # Internal redirection is a touch more difficult. request = context.request.copy_get() # Preserve the user's original request data, such as cookies. request.path = self._handler # Point the internal request at the authentication endpoint. request.environ['HTTP_REFERER'] = context.request.path_qs # Inform authentication where the user was. response = request.send(context.app) # Perform the internal redirect. response.status_int = context.response.status_int # Match the status to ensure browser caching not applied. context.response = response # Override the current (failed) response. # Authentication Extension Callbacks def authenticate(self, context, identifier, credential=None, force=False): """Authenticate a user. Sets the current user in the session, if configured to do so. You may omit a cedential and force authentication as a given user, if desired. The context attribute and session attributes, if configured, are updated and available for use immediately after the call to this function. Returns `True` on success, `False` otherwise. """ if force: user = self._lookup(identifier) if self._lookup else identifier else: result = self._authenticate(context, identifier, credential) if result is None or result[1] is None: log.debug("Authentication failed.") return False else: identifier, user = result log.debug("Authentication successful.") if self._session: self.__write(context.session, self._session, identifier) return True def deauthenticate(self, context, nuke=False): """Force logout. The context variable for the user is immediately deleted, and session variable cleared, as configured. Additionally, this function may also invalidate (clear) the current session, if requested. """ if nuke: context.session.invalidate() if self._session: self.__write(context.session, self._session, None) # Internal Use Utilities @staticmethod def __write(container, target, value): while '.' in target: segment, _, target = target.partition('.') container = getattr(container, segment) setattr(container, target, value)
{ "repo_name": "marrow/web.security", "path": "web/ext/auth.py", "copies": "1", "size": "6665", "license": "mit", "hash": 566941859449485500, "line_mean": 30.8899521531, "line_max": 114, "alpha_frac": 0.7332333083, "autogenerated": false, "ratio": 4.109124537607891, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5342357845907891, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" from __future__ import annotations from collections.abc import Awaitable, Callable from datetime import timedelta import logging import secrets from typing import Final from urllib.parse import unquote from aiohttp import hdrs from aiohttp.web import Application, Request, StreamResponse, middleware import jwt from homeassistant.core import HomeAssistant, callback from homeassistant.util import dt as dt_util from .const import KEY_AUTHENTICATED, KEY_HASS_REFRESH_TOKEN_ID, KEY_HASS_USER _LOGGER = logging.getLogger(__name__) DATA_API_PASSWORD: Final = "api_password" DATA_SIGN_SECRET: Final = "http.auth.sign_secret" SIGN_QUERY_PARAM: Final = "authSig" @callback def async_sign_path( hass: HomeAssistant, refresh_token_id: str, path: str, expiration: timedelta ) -> str: """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = secrets.token_hex() now = dt_util.utcnow() encoded = jwt.encode( { "iss": refresh_token_id, "path": unquote(path), "iat": now, "exp": now + expiration, }, secret, algorithm="HS256", ) return f"{path}?{SIGN_QUERY_PARAM}={encoded.decode()}" @callback def setup_auth(hass: HomeAssistant, app: Application) -> None: """Create auth middleware for the app.""" async def async_validate_auth_header(request: Request) -> bool: """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ try: auth_type, auth_val = request.headers.get(hdrs.AUTHORIZATION, "").split( " ", 1 ) except ValueError: # If no space in authorization header return False if auth_type != "Bearer": return False refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user request[KEY_HASS_REFRESH_TOKEN_ID] = refresh_token.id return True async def async_validate_signed_request(request: Request) -> bool: """Validate a signed request.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=["HS256"], options={"verify_iss": False} ) except jwt.InvalidTokenError: return False if claims["path"] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims["iss"]) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user request[KEY_HASS_REFRESH_TOKEN_ID] = refresh_token.id return True @middleware async def auth_middleware( request: Request, handler: Callable[[Request], Awaitable[StreamResponse]] ) -> StreamResponse: """Authenticate as middleware.""" authenticated = False if hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header( request ): authenticated = True auth_type = "bearer token" # We first start with a string check to avoid parsing query params # for every request. elif ( request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request) ): authenticated = True auth_type = "signed request" if authenticated: _LOGGER.debug( "Authenticated %s for %s using %s", request.remote, request.path, auth_type, ) request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware)
{ "repo_name": "home-assistant/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "2", "size": "4259", "license": "apache-2.0", "hash": 2317921701469235000, "line_mean": 28.1712328767, "line_max": 86, "alpha_frac": 0.6114111294, "autogenerated": false, "ratio": 4.2847082494969815, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5896119378896981, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import asyncio import base64 import hmac import logging from aiohttp import hdrs from aiohttp.web import middleware from homeassistant.const import HTTP_HEADER_HA_AUTH from .util import get_real_ip from .const import KEY_TRUSTED_NETWORKS, KEY_AUTHENTICATED DATA_API_PASSWORD = 'api_password' _LOGGER = logging.getLogger(__name__) @middleware @asyncio.coroutine def auth_middleware(request, handler): """Authenticate as middleware.""" # If no password set, just always set authenticated=True if request.app['hass'].http.api_password is None: request[KEY_AUTHENTICATED] = True return handler(request) # Check authentication authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers and validate_password( request, request.headers[HTTP_HEADER_HA_AUTH])): # A valid auth header has been set authenticated = True elif (DATA_API_PASSWORD in request.query and validate_password(request, request.query[DATA_API_PASSWORD])): authenticated = True elif (hdrs.AUTHORIZATION in request.headers and validate_authorization_header(request)): authenticated = True elif is_trusted_ip(request): authenticated = True request[KEY_AUTHENTICATED] = authenticated return handler(request) def is_trusted_ip(request): """Test if request is from a trusted ip.""" ip_addr = get_real_ip(request) return ip_addr and any( ip_addr in trusted_network for trusted_network in request.app[KEY_TRUSTED_NETWORKS]) def validate_password(request, api_password): """Test if password is valid.""" return hmac.compare_digest( api_password, request.app['hass'].http.api_password) def validate_authorization_header(request): """Test an authorization header if valid password.""" if hdrs.AUTHORIZATION not in request.headers: return False auth_type, auth = request.headers.get(hdrs.AUTHORIZATION).split(' ', 1) if auth_type != 'Basic': return False decoded = base64.b64decode(auth).decode('utf-8') username, password = decoded.split(':', 1) if username != 'homeassistant': return False return validate_password(request, password)
{ "repo_name": "ewandor/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "3", "size": "2304", "license": "apache-2.0", "hash": 3529250619101069300, "line_mean": 26.7590361446, "line_max": 75, "alpha_frac": 0.6883680556, "autogenerated": false, "ratio": 4.173913043478261, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6362281099078261, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import asyncio import base64 import hmac import logging from aiohttp import hdrs from homeassistant.const import HTTP_HEADER_HA_AUTH from .util import get_real_ip from .const import KEY_TRUSTED_NETWORKS, KEY_AUTHENTICATED DATA_API_PASSWORD = 'api_password' _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def auth_middleware(app, handler): """Authenticate as middleware.""" # If no password set, just always set authenticated=True if app['hass'].http.api_password is None: @asyncio.coroutine def no_auth_middleware_handler(request): """Auth middleware to approve all requests.""" request[KEY_AUTHENTICATED] = True return handler(request) return no_auth_middleware_handler @asyncio.coroutine def auth_middleware_handler(request): """Auth middleware to check authentication.""" # Auth code verbose on purpose authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers and validate_password( request, request.headers[HTTP_HEADER_HA_AUTH])): # A valid auth header has been set authenticated = True elif (DATA_API_PASSWORD in request.query and validate_password(request, request.query[DATA_API_PASSWORD])): authenticated = True elif (hdrs.AUTHORIZATION in request.headers and validate_authorization_header(request)): authenticated = True elif is_trusted_ip(request): authenticated = True request[KEY_AUTHENTICATED] = authenticated return handler(request) return auth_middleware_handler def is_trusted_ip(request): """Test if request is from a trusted ip.""" ip_addr = get_real_ip(request) return ip_addr and any( ip_addr in trusted_network for trusted_network in request.app[KEY_TRUSTED_NETWORKS]) def validate_password(request, api_password): """Test if password is valid.""" return hmac.compare_digest( api_password, request.app['hass'].http.api_password) def validate_authorization_header(request): """Test an authorization header if valid password.""" if hdrs.AUTHORIZATION not in request.headers: return False auth_type, auth = request.headers.get(hdrs.AUTHORIZATION).split(' ', 1) if auth_type != 'Basic': return False decoded = base64.b64decode(auth).decode('utf-8') username, password = decoded.split(':', 1) if username != 'homeassistant': return False return validate_password(request, password)
{ "repo_name": "stefan-jonasson/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "1", "size": "2664", "license": "mit", "hash": 2746233775085359600, "line_mean": 27.9565217391, "line_max": 76, "alpha_frac": 0.661036036, "autogenerated": false, "ratio": 4.374384236453202, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 92 }
"""Authentication for HTTP component.""" import asyncio import hmac import logging from homeassistant.const import HTTP_HEADER_HA_AUTH from .util import get_real_ip from .const import KEY_TRUSTED_NETWORKS, KEY_AUTHENTICATED DATA_API_PASSWORD = 'api_password' _LOGGER = logging.getLogger(__name__) @asyncio.coroutine def auth_middleware(app, handler): """Authenticate as middleware.""" # If no password set, just always set authenticated=True if app['hass'].http.api_password is None: @asyncio.coroutine def no_auth_middleware_handler(request): """Auth middleware to approve all requests.""" request[KEY_AUTHENTICATED] = True return handler(request) return no_auth_middleware_handler @asyncio.coroutine def auth_middleware_handler(request): """Auth middleware to check authentication.""" # Auth code verbose on purpose authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers and validate_password( request, request.headers[HTTP_HEADER_HA_AUTH])): # A valid auth header has been set authenticated = True elif (DATA_API_PASSWORD in request.GET and validate_password(request, request.GET[DATA_API_PASSWORD])): authenticated = True elif is_trusted_ip(request): authenticated = True request[KEY_AUTHENTICATED] = authenticated return handler(request) return auth_middleware_handler def is_trusted_ip(request): """Test if request is from a trusted ip.""" ip_addr = get_real_ip(request) return ip_addr and any( ip_addr in trusted_network for trusted_network in request.app[KEY_TRUSTED_NETWORKS]) def validate_password(request, api_password): """Test if password is valid.""" return hmac.compare_digest( api_password, request.app['hass'].http.api_password)
{ "repo_name": "shaftoe/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "3", "size": "1964", "license": "apache-2.0", "hash": 3896402517389430300, "line_mean": 28.7575757576, "line_max": 74, "alpha_frac": 0.6583503055, "autogenerated": false, "ratio": 4.345132743362832, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 66 }
"""Authentication for HTTP component.""" import base64 import hmac import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeassistant.core import callback from homeassistant.util import dt as dt_util from .const import KEY_AUTHENTICATED, KEY_REAL_IP _LOGGER = logging.getLogger(__name__) DATA_API_PASSWORD = 'api_password' DATA_SIGN_SECRET = 'http.auth.sign_secret' SIGN_QUERY_PARAM = 'authSig' @callback def async_sign_path(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = generate_secret() now = dt_util.utcnow() return "{}?{}={}".format(path, SIGN_QUERY_PARAM, jwt.encode({ 'iss': refresh_token_id, 'path': path, 'iat': now, 'exp': now + expiration, }, secret, algorithm='HS256').decode()) @callback def setup_auth(app, trusted_networks, api_password): """Create auth middleware for the app.""" old_auth_warning = set() @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers or DATA_API_PASSWORD in request.query): if request.path not in old_auth_warning: _LOGGER.log( logging.INFO if api_password else logging.WARNING, 'You need to use a bearer token to access %s from %s', request.path, request[KEY_REAL_IP]) old_auth_warning.add(request.path) if (hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header(request, api_password)): # it included both use_auth and api_password Basic auth authenticated = True # We first start with a string check to avoid parsing query params # for every request. elif (request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request)): authenticated = True elif (api_password and HTTP_HEADER_HA_AUTH in request.headers and hmac.compare_digest( api_password.encode('utf-8'), request.headers[HTTP_HEADER_HA_AUTH].encode('utf-8'))): # A valid auth header has been set authenticated = True request['hass_user'] = await legacy_api_password.async_get_user( app['hass']) elif (api_password and DATA_API_PASSWORD in request.query and hmac.compare_digest( api_password.encode('utf-8'), request.query[DATA_API_PASSWORD].encode('utf-8'))): authenticated = True request['hass_user'] = await legacy_api_password.async_get_user( app['hass']) elif _is_trusted_ip(request, trusted_networks): users = await app['hass'].auth.async_get_users() for user in users: if user.is_owner: request['hass_user'] = user authenticated = True break request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware) def _is_trusted_ip(request, trusted_networks): """Test if request is from a trusted ip.""" ip_addr = request[KEY_REAL_IP] return any( ip_addr in trusted_network for trusted_network in trusted_networks) def validate_password(request, api_password): """Test if password is valid.""" return hmac.compare_digest( api_password.encode('utf-8'), request.app['hass'].http.api_password.encode('utf-8')) async def async_validate_auth_header(request, api_password=None): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ if hdrs.AUTHORIZATION not in request.headers: return False try: auth_type, auth_val = \ request.headers.get(hdrs.AUTHORIZATION).split(' ', 1) except ValueError: # If no space in authorization header return False hass = request.app['hass'] if auth_type == 'Bearer': refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request['hass_refresh_token'] = refresh_token request['hass_user'] = refresh_token.user return True if auth_type == 'Basic' and api_password is not None: decoded = base64.b64decode(auth_val).decode('utf-8') try: username, password = decoded.split(':', 1) except ValueError: # If no ':' in decoded return False if username != 'homeassistant': return False if not hmac.compare_digest(api_password.encode('utf-8'), password.encode('utf-8')): return False request['hass_user'] = await legacy_api_password.async_get_user(hass) return True return False async def async_validate_signed_request(request): """Validate a signed request.""" hass = request.app['hass'] secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=['HS256'], options={'verify_iss': False} ) except jwt.InvalidTokenError: return False if claims['path'] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims['iss']) if refresh_token is None: return False request['hass_refresh_token'] = refresh_token request['hass_user'] = refresh_token.user return True
{ "repo_name": "HydrelioxGitHub/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "1", "size": "6269", "license": "apache-2.0", "hash": -2117000514953568800, "line_mean": 30.1890547264, "line_max": 79, "alpha_frac": 0.612856915, "autogenerated": false, "ratio": 4.201742627345845, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5314599542345845, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import base64 import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.const import HTTP_HEADER_HA_AUTH from homeassistant.core import callback from homeassistant.util import dt as dt_util from .const import KEY_AUTHENTICATED, KEY_HASS_USER, KEY_REAL_IP _LOGGER = logging.getLogger(__name__) DATA_API_PASSWORD = "api_password" DATA_SIGN_SECRET = "http.auth.sign_secret" SIGN_QUERY_PARAM = "authSig" @callback def async_sign_path(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = generate_secret() now = dt_util.utcnow() return "{}?{}={}".format( path, SIGN_QUERY_PARAM, jwt.encode( { "iss": refresh_token_id, "path": path, "iat": now, "exp": now + expiration, }, secret, algorithm="HS256", ).decode(), ) @callback def setup_auth(hass, app): """Create auth middleware for the app.""" old_auth_warning = set() support_legacy = hass.auth.support_legacy if support_legacy: _LOGGER.warning("legacy_api_password support has been enabled.") trusted_networks = [] for prv in hass.auth.auth_providers: if prv.type == "trusted_networks": trusted_networks += prv.trusted_networks async def async_validate_auth_header(request): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ try: auth_type, auth_val = request.headers.get(hdrs.AUTHORIZATION).split(" ", 1) except ValueError: # If no space in authorization header return False if auth_type == "Bearer": refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user return True if auth_type == "Basic" and support_legacy: decoded = base64.b64decode(auth_val).decode("utf-8") try: username, password = decoded.split(":", 1) except ValueError: # If no ':' in decoded return False if username != "homeassistant": return False user = await legacy_api_password.async_validate_password(hass, password) if user is None: return False request[KEY_HASS_USER] = user _LOGGER.info( "Basic auth with api_password is going to deprecate," " please use a bearer token to access %s from %s", request.path, request[KEY_REAL_IP], ) old_auth_warning.add(request.path) return True return False async def async_validate_signed_request(request): """Validate a signed request.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=["HS256"], options={"verify_iss": False} ) except jwt.InvalidTokenError: return False if claims["path"] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims["iss"]) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user return True async def async_validate_trusted_networks(request): """Test if request is from a trusted ip.""" ip_addr = request[KEY_REAL_IP] if not any(ip_addr in trusted_network for trusted_network in trusted_networks): return False user = await hass.auth.async_get_owner() if user is None: return False request[KEY_HASS_USER] = user return True async def async_validate_legacy_api_password(request, password): """Validate api_password.""" user = await legacy_api_password.async_validate_password(hass, password) if user is None: return False request[KEY_HASS_USER] = user return True @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if HTTP_HEADER_HA_AUTH in request.headers or DATA_API_PASSWORD in request.query: if request.path not in old_auth_warning: _LOGGER.log( logging.INFO if support_legacy else logging.WARNING, "api_password is going to deprecate. You need to use a" " bearer token to access %s from %s", request.path, request[KEY_REAL_IP], ) old_auth_warning.add(request.path) if hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header( request ): # it included both use_auth and api_password Basic auth authenticated = True # We first start with a string check to avoid parsing query params # for every request. elif ( request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request) ): authenticated = True elif trusted_networks and await async_validate_trusted_networks(request): if request.path not in old_auth_warning: # When removing this, don't forget to remove the print logic # in http/view.py request["deprecate_warning_message"] = ( "Access from trusted networks without auth token is " "going to be removed in Home Assistant 0.96. Configure " "the trusted networks auth provider or use long-lived " "access tokens to access {} from {}".format( request.path, request[KEY_REAL_IP] ) ) old_auth_warning.add(request.path) authenticated = True elif ( support_legacy and HTTP_HEADER_HA_AUTH in request.headers and await async_validate_legacy_api_password( request, request.headers[HTTP_HEADER_HA_AUTH] ) ): authenticated = True elif ( support_legacy and DATA_API_PASSWORD in request.query and await async_validate_legacy_api_password( request, request.query[DATA_API_PASSWORD] ) ): authenticated = True request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware)
{ "repo_name": "fbradyirl/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "1", "size": "7407", "license": "apache-2.0", "hash": 3278703469062248000, "line_mean": 31.2043478261, "line_max": 88, "alpha_frac": 0.5763466991, "autogenerated": false, "ratio": 4.521978021978022, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5598324721078022, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import logging import secrets from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.core import callback from homeassistant.util import dt as dt_util from .const import KEY_AUTHENTICATED, KEY_HASS_REFRESH_TOKEN_ID, KEY_HASS_USER # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) DATA_API_PASSWORD = "api_password" DATA_SIGN_SECRET = "http.auth.sign_secret" SIGN_QUERY_PARAM = "authSig" @callback def async_sign_path(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = secrets.token_hex() now = dt_util.utcnow() encoded = jwt.encode( {"iss": refresh_token_id, "path": path, "iat": now, "exp": now + expiration}, secret, algorithm="HS256", ) return f"{path}?{SIGN_QUERY_PARAM}=" f"{encoded.decode()}" @callback def setup_auth(hass, app): """Create auth middleware for the app.""" async def async_validate_auth_header(request): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ try: auth_type, auth_val = request.headers.get(hdrs.AUTHORIZATION).split(" ", 1) except ValueError: # If no space in authorization header return False if auth_type != "Bearer": return False refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user request[KEY_HASS_REFRESH_TOKEN_ID] = refresh_token.id return True async def async_validate_signed_request(request): """Validate a signed request.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=["HS256"], options={"verify_iss": False} ) except jwt.InvalidTokenError: return False if claims["path"] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims["iss"]) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user request[KEY_HASS_REFRESH_TOKEN_ID] = refresh_token.id return True @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header( request ): authenticated = True auth_type = "bearer token" # We first start with a string check to avoid parsing query params # for every request. elif ( request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request) ): authenticated = True auth_type = "signed request" if authenticated: _LOGGER.debug( "Authenticated %s for %s using %s", request.remote, request.path, auth_type, ) request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware)
{ "repo_name": "turbokongen/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "5", "size": "3757", "license": "apache-2.0", "hash": -6646733706166692000, "line_mean": 27.679389313, "line_max": 87, "alpha_frac": 0.6100612191, "autogenerated": false, "ratio": 4.160575858250277, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7270637077350277, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.auth.util import generate_secret from homeassistant.core import callback from homeassistant.util import dt as dt_util from .const import KEY_AUTHENTICATED, KEY_HASS_USER, KEY_REAL_IP # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) DATA_API_PASSWORD = "api_password" DATA_SIGN_SECRET = "http.auth.sign_secret" SIGN_QUERY_PARAM = "authSig" @callback def async_sign_path(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = generate_secret() now = dt_util.utcnow() return "{}?{}={}".format( path, SIGN_QUERY_PARAM, jwt.encode( { "iss": refresh_token_id, "path": path, "iat": now, "exp": now + expiration, }, secret, algorithm="HS256", ).decode(), ) @callback def setup_auth(hass, app): """Create auth middleware for the app.""" async def async_validate_auth_header(request): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ try: auth_type, auth_val = request.headers.get(hdrs.AUTHORIZATION).split(" ", 1) except ValueError: # If no space in authorization header return False if auth_type != "Bearer": return False refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user return True async def async_validate_signed_request(request): """Validate a signed request.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=["HS256"], options={"verify_iss": False} ) except jwt.InvalidTokenError: return False if claims["path"] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims["iss"]) if refresh_token is None: return False request[KEY_HASS_USER] = refresh_token.user return True @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header( request ): authenticated = True auth_type = "bearer token" # We first start with a string check to avoid parsing query params # for every request. elif ( request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request) ): authenticated = True auth_type = "signed request" if authenticated: _LOGGER.debug( "Authenticated %s for %s using %s", request[KEY_REAL_IP], request.path, auth_type, ) request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware)
{ "repo_name": "joopert/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "2", "size": "3773", "license": "apache-2.0", "hash": 3604284060827295000, "line_mean": 26.3405797101, "line_max": 87, "alpha_frac": 0.5883912006, "autogenerated": false, "ratio": 4.3318025258323765, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5920193726432377, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import base64 import hmac import logging from aiohttp import hdrs from aiohttp.web import middleware import jwt from homeassistant.core import callback from homeassistant.const import HTTP_HEADER_HA_AUTH from homeassistant.auth.providers import legacy_api_password from homeassistant.auth.util import generate_secret from homeassistant.util import dt as dt_util from .const import KEY_AUTHENTICATED, KEY_REAL_IP DATA_API_PASSWORD = 'api_password' DATA_SIGN_SECRET = 'http.auth.sign_secret' SIGN_QUERY_PARAM = 'authSig' _LOGGER = logging.getLogger(__name__) @callback def async_sign_path(hass, refresh_token_id, path, expiration): """Sign a path for temporary access without auth header.""" secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: secret = hass.data[DATA_SIGN_SECRET] = generate_secret() now = dt_util.utcnow() return "{}?{}={}".format(path, SIGN_QUERY_PARAM, jwt.encode({ 'iss': refresh_token_id, 'path': path, 'iat': now, 'exp': now + expiration, }, secret, algorithm='HS256').decode()) @callback def setup_auth(app, trusted_networks, api_password): """Create auth middleware for the app.""" old_auth_warning = set() @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if (HTTP_HEADER_HA_AUTH in request.headers or DATA_API_PASSWORD in request.query): if request.path not in old_auth_warning: _LOGGER.log( logging.INFO if api_password else logging.WARNING, 'You need to use a bearer token to access %s from %s', request.path, request[KEY_REAL_IP]) old_auth_warning.add(request.path) if (hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header(request, api_password)): # it included both use_auth and api_password Basic auth authenticated = True # We first start with a string check to avoid parsing query params # for every request. elif (request.method == "GET" and SIGN_QUERY_PARAM in request.query and await async_validate_signed_request(request)): authenticated = True elif (api_password and HTTP_HEADER_HA_AUTH in request.headers and hmac.compare_digest( api_password.encode('utf-8'), request.headers[HTTP_HEADER_HA_AUTH].encode('utf-8'))): # A valid auth header has been set authenticated = True request['hass_user'] = await legacy_api_password.async_get_user( app['hass']) elif (api_password and DATA_API_PASSWORD in request.query and hmac.compare_digest( api_password.encode('utf-8'), request.query[DATA_API_PASSWORD].encode('utf-8'))): authenticated = True request['hass_user'] = await legacy_api_password.async_get_user( app['hass']) elif _is_trusted_ip(request, trusted_networks): users = await app['hass'].auth.async_get_users() for user in users: if user.is_owner: request['hass_user'] = user break authenticated = True request[KEY_AUTHENTICATED] = authenticated return await handler(request) app.middlewares.append(auth_middleware) def _is_trusted_ip(request, trusted_networks): """Test if request is from a trusted ip.""" ip_addr = request[KEY_REAL_IP] return any( ip_addr in trusted_network for trusted_network in trusted_networks) def validate_password(request, api_password): """Test if password is valid.""" return hmac.compare_digest( api_password.encode('utf-8'), request.app['hass'].http.api_password.encode('utf-8')) async def async_validate_auth_header(request, api_password=None): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ if hdrs.AUTHORIZATION not in request.headers: return False try: auth_type, auth_val = \ request.headers.get(hdrs.AUTHORIZATION).split(' ', 1) except ValueError: # If no space in authorization header return False hass = request.app['hass'] if auth_type == 'Bearer': refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request['hass_refresh_token'] = refresh_token request['hass_user'] = refresh_token.user return True if auth_type == 'Basic' and api_password is not None: decoded = base64.b64decode(auth_val).decode('utf-8') try: username, password = decoded.split(':', 1) except ValueError: # If no ':' in decoded return False if username != 'homeassistant': return False if not hmac.compare_digest(api_password.encode('utf-8'), password.encode('utf-8')): return False request['hass_user'] = await legacy_api_password.async_get_user(hass) return True return False async def async_validate_signed_request(request): """Validate a signed request.""" hass = request.app['hass'] secret = hass.data.get(DATA_SIGN_SECRET) if secret is None: return False signature = request.query.get(SIGN_QUERY_PARAM) if signature is None: return False try: claims = jwt.decode( signature, secret, algorithms=['HS256'], options={'verify_iss': False} ) except jwt.InvalidTokenError: return False if claims['path'] != request.path: return False refresh_token = await hass.auth.async_get_refresh_token(claims['iss']) if refresh_token is None: return False request['hass_refresh_token'] = refresh_token request['hass_user'] = refresh_token.user return True
{ "repo_name": "tinloaf/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "1", "size": "6262", "license": "apache-2.0", "hash": -5321763017716089000, "line_mean": 30, "line_max": 79, "alpha_frac": 0.6135419994, "autogenerated": false, "ratio": 4.1942397856664435, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5307781785066443, "avg_score": null, "num_lines": null }
"""Authentication for HTTP component.""" import base64 import hmac import logging from aiohttp import hdrs from aiohttp.web import middleware from homeassistant.core import callback from homeassistant.const import HTTP_HEADER_HA_AUTH from .const import KEY_AUTHENTICATED, KEY_REAL_IP DATA_API_PASSWORD = 'api_password' _LOGGER = logging.getLogger(__name__) @callback def setup_auth(app, trusted_networks, use_auth, support_legacy=False, api_password=None): """Create auth middleware for the app.""" old_auth_warning = set() @middleware async def auth_middleware(request, handler): """Authenticate as middleware.""" authenticated = False if use_auth and (HTTP_HEADER_HA_AUTH in request.headers or DATA_API_PASSWORD in request.query): if request.path not in old_auth_warning: _LOGGER.log( logging.INFO if support_legacy else logging.WARNING, 'You need to use a bearer token to access %s from %s', request.path, request[KEY_REAL_IP]) old_auth_warning.add(request.path) legacy_auth = (not use_auth or support_legacy) and api_password if (hdrs.AUTHORIZATION in request.headers and await async_validate_auth_header( request, api_password if legacy_auth else None)): # it included both use_auth and api_password Basic auth authenticated = True elif (legacy_auth and HTTP_HEADER_HA_AUTH in request.headers and hmac.compare_digest( api_password.encode('utf-8'), request.headers[HTTP_HEADER_HA_AUTH].encode('utf-8'))): # A valid auth header has been set authenticated = True elif (legacy_auth and DATA_API_PASSWORD in request.query and hmac.compare_digest( api_password.encode('utf-8'), request.query[DATA_API_PASSWORD].encode('utf-8'))): authenticated = True elif _is_trusted_ip(request, trusted_networks): authenticated = True elif not use_auth and api_password is None: # If neither password nor auth_providers set, # just always set authenticated=True authenticated = True request[KEY_AUTHENTICATED] = authenticated return await handler(request) async def auth_startup(app): """Initialize auth middleware when app starts up.""" app.middlewares.append(auth_middleware) app.on_startup.append(auth_startup) def _is_trusted_ip(request, trusted_networks): """Test if request is from a trusted ip.""" ip_addr = request[KEY_REAL_IP] return any( ip_addr in trusted_network for trusted_network in trusted_networks) def validate_password(request, api_password): """Test if password is valid.""" return hmac.compare_digest( api_password.encode('utf-8'), request.app['hass'].http.api_password.encode('utf-8')) async def async_validate_auth_header(request, api_password=None): """ Test authorization header against access token. Basic auth_type is legacy code, should be removed with api_password. """ if hdrs.AUTHORIZATION not in request.headers: return False try: auth_type, auth_val = \ request.headers.get(hdrs.AUTHORIZATION).split(' ', 1) except ValueError: # If no space in authorization header return False if auth_type == 'Bearer': hass = request.app['hass'] refresh_token = await hass.auth.async_validate_access_token(auth_val) if refresh_token is None: return False request['hass_user'] = refresh_token.user return True if auth_type == 'Basic' and api_password is not None: decoded = base64.b64decode(auth_val).decode('utf-8') try: username, password = decoded.split(':', 1) except ValueError: # If no ':' in decoded return False if username != 'homeassistant': return False return hmac.compare_digest(api_password.encode('utf-8'), password.encode('utf-8')) return False
{ "repo_name": "persandstrom/home-assistant", "path": "homeassistant/components/http/auth.py", "copies": "1", "size": "4322", "license": "apache-2.0", "hash": 998796629718866600, "line_mean": 31.7424242424, "line_max": 77, "alpha_frac": 0.6154558075, "autogenerated": false, "ratio": 4.3480885311871225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5463544338687123, "avg_score": null, "num_lines": null }
"""Authentication for Magpy backend.""" import tornado.auth import tornado.web # pylint: disable=W0404 import tornado.gen import json from bson import json_util from bson.objectid import ObjectId from functools import partial from magpy.server.database import DatabaseMixin from magpy.server.utils import dejsonify import six import base64 # pylint: disable=R0904,W0613,R0913 def permission_required(operation): """Decorator that makes the decorated function require permission to do the operation. operation - create, read, update or delete. """ def decorator(func): """Wraps the method with autentication.""" def wrapper(self, resource, *args, **kwargs): """If successful, apply the arguments and use it.""" success = partial(func, self, resource, *args, **kwargs) presource = resource poperation = operation if resource == '_model' and operation == 'read': if args: model = args[0] if model: presource = model if resource == "_history": arguments = self.request.arguments if 'document_model' in arguments: presource = arguments['document_model'][0] poperation = "delete" else: # We got _history but without 'document_model' raise tornado.web.HTTPError( 400, "Missing argument - " "history requires 'document_model'.") return self.check_permission(success=success, resource=presource, permission=poperation) return wrapper return decorator class AuthenticationMixin(object): """ Provides authentication checks for the api. """ def check_permissions(self, success, failure=None, permissions=None): # pylint: disable=W0221 """Check that the user is allowed to use the resources defined in permissions. permissions - a dictionary with each entry having a resource type as the key, and a list of permissions as the values, e.g. {'author': ['read', 'create', 'update', 'delete']} success - the callback to run on success. failure - the callback to run on failure. """ if not permissions: permissions = {arg: dejsonify(self.request.arguments[arg][0]) for arg in self.request.arguments} if not failure: failure = self.permission_denied # 1. get user # 2. get relevant groups # 2. get models # 3. combine them together # 4. Test it against the input if not self.get_secure_cookie("user"): # We are not logged in, go to the next stage return self._get_models_for_check_perms( groups=None, error=None, user=None, permissions=permissions, success=success, failure=failure) callback = partial(self._get_relevant_groups, permissions=permissions, success=success, failure=failure) coll = self.get_collection('_user') coll.find_one({'_id': self.get_secure_cookie("user")}, callback=callback, fields=['_permissions']) def _get_relevant_groups(self, user, error, permissions, success, failure): """Get relevant groups. Result is a list of results, e.g.: [{u'_id': u'citations_editors', u'_permissions': {u'author': {u'update': {u'author': True}}}}] """ callback = partial(self._get_models_for_check_perms, user=user, permissions=permissions, success=success, failure=failure) groups = self.get_collection('_group') model_names = permissions.keys() or_query = [ { '_permissions.%s' % model_name: { "$exists": True}} for model_name in model_names] groups.find( {'members': user['_id'], '$or': or_query}, ['_permissions']).to_list(callback=callback) def _get_models_for_check_perms(self, groups, error, user, permissions, success, failure): """Get the required models to satisfy permissions.""" callback = partial(self._do_check_permissions, permissions=permissions, user=user, groups=groups, success=success, failure=failure) models = self.get_collection('_model') models.find( spec={ '_id': { '$in': tuple(permissions.keys())}}, fields=['_permissions']).to_list(callback=callback) @staticmethod def _overlay_permissions(models, user, groups): """Combine the user, group and model permissions. 1. We start with default permissions of read-only, 2. We overlay any permissions set in the model, 3. We overlay any permissions in a group, 4. We overlay any permissions in the user. """ permissions = {} for model in models: model_permissions = { 'read': True, 'create': False, 'update': False, 'delete': False} if '_permissions' in model: model_permissions.update(model['_permissions']) if groups: for group in groups: if model['_id'] in group['_permissions']: model_permissions.update( group['_permissions'][model['_id']]) if user: if '_permissions' in user: if model['_id'] in user['_permissions']: model_permissions.update( user['_permissions'][model['_id']]) permissions[model['_id']] = model_permissions return permissions def _do_check_permissions(self, models, error, user, groups, permissions, success, failure): """Process the stored permissions.""" stored_permissions = self._overlay_permissions(models, user, groups) missing_permissions = {} for resource, perm_list in six.iteritems(permissions): for perm in perm_list: if not stored_permissions[resource][perm]: if resource in missing_permissions: missing_permissions[resource].append(perm) else: missing_permissions[resource] = [perm] if missing_permissions: return failure([False, missing_permissions]) return success([True, missing_permissions]) def check_permission(self, resource, permission, success, failure=None): # pylint: disable=W0221 """Check that the user is allowed to use the resource. resource - the model name of the resource. permission - create, read, update or delete. success - the callback to run on success. failure - the callback to run on failure. """ if not failure: failure = self.permission_denied if not self.get_secure_cookie("user"): # We are not logged in, go to the next stage return self._request_modelp(resource, permission, success, failure) callback = partial(self._check_user, resource=resource, permission=permission, success=success, failure=failure) coll = self.get_collection('_user') coll.find_one({'_id': self.get_secure_cookie("user")}, callback=callback) def _check_user(self, user, error, resource, permission, success, failure): """Check if the user has the required permission.""" if not user: return self._request_modelp(resource, permission, success, failure) if '_permissions' not in user: return self._request_modelp(resource, permission, success, failure) if resource not in user['_permissions']: return self._request_modelp(resource, permission, success, failure) if permission in user['_permissions'][resource]: permission_value = \ user['_permissions'][resource].get(permission) if permission_value: return success() else: return failure() return self._request_modelp(resource, permission, success, failure) def _request_modelp(self, resource, permission, success, failure): """Get the model from the database.""" coll = self.get_collection('_model') callback = partial(self._check_model, permission=permission, on_success=success, on_failure=failure) coll.find_one({'_id': resource}, callback=callback) #def _check_model(self, model, permission, success, failure): def _check_model(self, model, error, permission, on_success, on_failure, *args, **kwargs): """See that permissions there are in the model.""" if not model: return on_failure() if '_permissions' not in model: return self._standard(permission, on_success, on_failure) if permission in model['_permissions']: if model['_permissions'][permission]: return on_success() else: return on_failure() return self._standard(permission, on_success, on_failure) @staticmethod def _standard(permission, success, failure): """Give the standard answer.""" if permission == 'read': return success() else: return failure() @staticmethod def permission_denied(details=None): """The user should not access this resource. A useful default failure callback.""" # TODO: do something with details raise tornado.web.HTTPError(401) class AuthPermissionsHandler(tornado.web.RequestHandler, DatabaseMixin, AuthenticationMixin): """Check permissions. """ @tornado.web.asynchronous def get(self): # pylint: disable=W0221 success = self._return_instance failure = self._return_instance self.check_permissions(success, failure) def _return_instance(self, instance, error=None): """Return a single instance or anything else that can become JSON.""" self.set_header("Content-Type", "application/json; charset=UTF-8") json_response = json.dumps(instance, default=json_util.default) if six.PY3: json_response = bytes(json_response, 'utf8') self.write(json_response) self.finish() class AuthPermissionHandler(tornado.web.RequestHandler, DatabaseMixin, AuthenticationMixin): """Check permissions. """ @tornado.web.asynchronous def get(self, resource, permission): # pylint: disable=W0221 success = partial(self._return_instance, instance=True) failure = partial(self._return_instance, instance=False) self.check_permission(resource, permission, success, failure) def _return_instance(self, instance, error=None): """Return a single instance or anything else that can become JSON.""" self.set_header("Content-Type", "application/json; charset=UTF-8") self.write(json.dumps(instance, default=json_util.default)) self.finish() class WhoAmIMixin(object): """Answer who am I queries - get user information.""" # pylint: disable=R0903 @tornado.web.asynchronous def who_am_i(self, success, failure=None): """If logged in, find user from cookie.""" if not self.get_secure_cookie("user"): if failure: return failure() else: raise tornado.web.HTTPError(404) coll = self.get_collection('_user') coll.find_one({'_id': self.get_secure_cookie("user")}, callback=success) class AuthWhoAmIHandler(tornado.web.RequestHandler, DatabaseMixin, WhoAmIMixin): """Answer who am I queries - get user information.""" @tornado.web.asynchronous def get(self): return self.who_am_i(self._return_user) def _return_user(self, instance, error): """Return a single instance or anything else that can become JSON.""" if not instance: raise tornado.web.HTTPError(404) self.set_header("Content-Type", "application/json; charset=UTF-8") self.write(json.dumps(instance, default=json_util.default)) self.finish() class AuthWhoAreTheyHandler(tornado.web.RequestHandler, DatabaseMixin): @tornado.web.asynchronous def get(self): if self.get_argument('ids', None): ids = json.loads(self.get_argument('ids')[5:]) #self.resolve_ids_to_names(ids) coll = self.get_collection('_user') callback = partial(self._build_dictionary) coll.find(spec={'_id': {'$in': ids}}).to_list(callback=callback) else: self.set_header("Content-Type", "application/json; charset=UTF-8") empty_response = json.dumps({}, default=json_util.default) if six.PY3: empty_response = bytes(json_response, 'utf8') self.write(empty_response) self.finish() return def resolve_ids_to_names(self, ids): coll = self.get_collection('_user') callback = partial(self._build_dictionary) coll.find(spec={'_id': {'$in': ids}}).to_list(callback=callback) def _build_dictionary(self, result, error): resolved = {} for entry in result: if 'name' in entry.keys(): resolved[entry['_id']] = entry['name'] elif 'last_name' in entry.keys(): resolved[entry['_id']] = entry['last_name'] elif 'first_name' in entry.keys(): resolved[entry['_id']] = entry['first_name'] else: resolved[entry['_id']] = entry['_id'] self.set_header("Content-Type", "application/json; charset=UTF-8") self.write(json.dumps(resolved, default=json_util.default)) self.finish() return class AuthLogoutHandler(tornado.web.RequestHandler): """Handle logouts.""" def get(self): self.clear_cookie("user") self.redirect(self.get_argument("next", "/")) class AuthLoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin, DatabaseMixin): """Handle logins.""" @tornado.gen.coroutine @tornado.web.asynchronous def get(self): print('arguments...') print(self.request.arguments) if self.get_argument('code', False): next_page = self.get_argument('state', '/') access_token = yield self.get_authenticated_user( redirect_uri = base64.b64decode(self.settings['login_redirect']), code = self.get_argument('code')) http = self.get_auth_http_client() callback = partial(self._on_auth, next_page=next_page) http.fetch("https://www.googleapis.com/oauth2/v2/userinfo", callback, headers = {'Authorization': 'Bearer %s' % access_token['access_token']}) else: #in tornado 3.2 this does not return a Future so we can't use yield #docs say it should do so if we can get up to a later version of tornado it might be better next_page = base64.b64encode(self.get_argument("next", "/")) self.authorize_redirect( redirect_uri = base64.b64decode(self.settings['login_redirect']), client_id = self.settings['google_oauth']['key'], scope = ['email', 'profile'], response_type = 'code', extra_params = {'approval_prompt': 'auto', 'state': next_page}) def _on_auth(self, resp, next_page): """Find the relevant user.""" user = json.loads(resp.body) if not user: raise tornado.web.HTTPError(500, "Google auth failed") coll = self.get_collection('_user') callback = partial(self._process_user, user=user, next_page=next_page) coll.find_one({'email': user["email"]}, callback=callback) def _process_user(self, result, error, user, next_page): print(user) """Process the mongo user and the request user""" if result is None: # User does not exist yet, create account. coll = self.get_collection('_user') callback = partial(self._set_cookie, next_page=next_page) coll.insert({'email': user["email"], 'name': user["name"], 'locale': user['locale'], 'first_name': user['given_name'], 'last_name': user['family_name'], '_id': str(ObjectId()) }, callback=callback) else: # User exists self._set_cookie(result["_id"], None, next_page) def _set_cookie(self, user_id, error, next_page): """Set the cookie to the user_id.""" self.set_secure_cookie("user", str(user_id)) self.redirect(base64.b64decode(next_page))
{ "repo_name": "zeth/magpy", "path": "magpy/server/auth.py", "copies": "2", "size": "19421", "license": "bsd-3-clause", "hash": 8835503655712473000, "line_mean": 37.842, "line_max": 103, "alpha_frac": 0.5214973482, "autogenerated": false, "ratio": 4.877197388247112, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6398694736447111, "avg_score": null, "num_lines": null }
"""Authentication for salesforce-reporting""" import requests import xml.dom.minidom try: # Python 3+ from html import escape except ImportError: from cgi import escape class Connection: """ A Salesforce connection for accessing the Salesforce Analytics API using the Password/Token authentication. This object is then used as the central object for passing report requests into Salesforce. By default the object assumes you are connection to a Production instance and using API v29.0 but both of these can be overridden to allow access to Sandbox instances and/or use a different API version. Parameters ---------- username: string the Salesforce username used for authentication password: string the Salesforce password used for authentication security_token: string the Salesforce security token used for authentication (normally tied to password) sandbox: boolean, default False whether or not the Salesforce instance connected to is a Sandbox api_version: string """ def __init__(self, username=None, password=None, security_token=None, sandbox=False, api_version='v29.0'): self.username = username self.password = password self.security_token = security_token self.sandbox = sandbox self.api_version = api_version self.login_details = self.login(self.username, self.password, self.security_token) self.token = self.login_details['oauth'] self.instance = self.login_details['instance'] self.headers = {'Authorization': 'OAuth {}'.format(self.token)} self.base_url = 'https://{}/services/data/v31.0/analytics'.format(self.instance) @staticmethod def element_from_xml_string(xml_string, element): xml_as_dom = xml.dom.minidom.parseString(xml_string) elements_by_name = xml_as_dom.getElementsByTagName(element) element_value = None if len(elements_by_name) > 0: element_value = elements_by_name[0].toxml().replace('<' + element + '>', '').replace( '</' + element + '>', '') return element_value @staticmethod def _get_login_url(is_sandbox, api_version): if is_sandbox: return 'https://{}.salesforce.com/services/Soap/u/{}'.format('test', api_version) else: return 'https://{}.salesforce.com/services/Soap/u/{}'.format('login', api_version) def login(self, username, password, security_token): username = escape(username) password = escape(password) url = self._get_login_url(self.sandbox, self.api_version) request_body = """<?xml version="1.0" encoding="utf-8" ?> <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <n1:login xmlns:n1="urn:partner.soap.sforce.com"> <n1:username>{username}</n1:username> <n1:password>{password}{token}</n1:password> </n1:login> </env:Body> </env:Envelope>""".format( username=username, password=password, token=security_token) request_headers = { 'content-type': 'text/xml', 'charset': 'UTF-8', 'SOAPAction': 'login' } response = requests.post(url, request_body, headers=request_headers) if response.status_code != 200: exception_code = self.element_from_xml_string(response.content, 'sf:exceptionCode') exception_msg = self.element_from_xml_string(response.content, 'sf:exceptionMessage') raise AuthenticationFailure(exception_code, exception_msg) oauth_token = self.element_from_xml_string(response.content, 'sessionId') server_url = self.element_from_xml_string(response.content, 'serverUrl') instance = (server_url.replace('http://', '') .replace('https://', '') .split('/')[0] .replace('-api', '')) return {'oauth': oauth_token, 'instance': instance} def _get_metadata(self, url): return requests.get(url + '/describe', headers=self.headers).json() def _get_report_filtered(self, url, filters): metadata_url = url.split('?')[0] metadata = self._get_metadata(metadata_url) for report_filter in filters: metadata["reportMetadata"]["reportFilters"].append(report_filter) return requests.post(url, headers=self.headers, json=metadata).json() def _get_report_all(self, url): return requests.post(url, headers=self.headers).json() def get_report(self, report_id, filters=None, details=True): """ Return the full JSON content of a Salesforce report, with or without filters. Parameters ---------- report_id: string Salesforce Id of target report filters: dict {field: filter}, optional details: boolean, default True Whether or not detail rows are included in report output Returns ------- report: JSON """ details = 'true' if details else 'false' url = '{}/reports/{}?includeDetails={}'.format(self.base_url, report_id, details) if filters: return self._get_report_filtered(url, filters) else: return self._get_report_all(url) def get_dashboard(self, dashboard_id): url = '{}/dashboards/{}/'.format(self.base_url, dashboard_id) return requests.get(url, headers=self.headers).json() class AuthenticationFailure(Exception): def __init__(self, code, msg): self.code = code self.msg = msg def __str__(self): return "{}: {}.".format(self.code, self.msg)
{ "repo_name": "cghall/salesforce-reporting", "path": "salesforce_reporting/login.py", "copies": "1", "size": "5960", "license": "mit", "hash": -7162925508853577000, "line_mean": 36.0186335404, "line_max": 110, "alpha_frac": 0.6157718121, "autogenerated": false, "ratio": 4.124567474048443, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010860107585022615, "num_lines": 161 }
""" Authentication library ====================== A base authentication & authorization module. Includes the base class BaseAuth. Authentication and authorization in NIPAP ----------------------------------------- NIPAP offers basic authentication with two different backends, a simple two-level authorization model and a trust-system for simplifying system integration. Readonly users are only authorized to run queries which do not modify any data in the database. No further granularity of access control is offered at this point. Trusted users can perform operations which will be logged as performed by another user. This feature is meant for system integration, for example to be used by a NIPAP client which have its own means of authentication users; say for example a web application supporting the NTLM single sign-on feature. By letting the web application use a trusted account to authenticate against the NIPAP service, it can specify the username of the end-user, so that audit logs will be written with the correct information. Without the trusted-bit, all queries performed by end-users through this system would look like they were performed by the system itself. The NIPAP auth system also has a concept of authoritative source. The authoritative source is a string which simply defines what system is the authoritative source of data for a prefix. Well-behaved clients SHOULD present a warning to the user when trying to alter a prefix with an authoritative source different than the system itself, as other system might depend on the information being unchanged. This is however, by no means enforced by the NIPAP service. Authentication backends ----------------------- Two authentication backends are shipped with NIPAP: * LdapAuth - authenticates users against an LDAP server * SqliteAuth - authenticates users against a local SQLite-database The authentication classes presented here are used both in the NIPAP web UI and in the XML-RPC backend. So far only the SqliteAuth backend supports trusted and readonly users. What authentication backend to use can be specified by suffixing the username with @`backend`, where `backend` is set in the configuration file. If not defined, a (configurable) default backend is used. Authentication options ---------------------- With each NIPAP query authentication options can be specified. The authentication options are passed as a dict with the following keys taken into account: * :attr:`authoritative_source` - Authoritative source for the query. * :attr:`username` - Username to impersonate, requires authentication as \ trusted user. * :attr:`full_name` - Full name of impersonated user. * :attr:`readonly` - True for read-only users Classes ------- """ import logging from datetime import datetime, timedelta import hashlib from nipapconfig import NipapConfig # Used by auth modules import sqlite3 import string import random try: import ldap except ImportError: ldap = None class AuthFactory: """ An factory for authentication backends. """ _logger = None _config = None _auth_cache = {} _backends = {} def __init__(self): """ Constructor. """ # Initialize stuff. self._config = NipapConfig() self._logger = logging.getLogger(self.__class__.__name__) self._init_backends() def _init_backends(self): """ Initialize auth backends. """ # fetch auth backends from config file self._backends = {} for section in self._config.sections(): # does the section define an auth backend? section_components = section.rsplit('.', 1) if section_components[0] == 'auth.backends': auth_backend = section_components[1] self._backends[auth_backend] = eval(self._config.get(section, 'type')) self._logger.debug("Registered auth backends %s" % str(self._backends)) def reload(self): """ Reload AuthFactory. """ self._auth_cache = {} self._init_backends() def get_auth(self, username, password, authoritative_source, auth_options=None): """ Returns an authentication object. Examines the auth backend given after the '@' in the username and returns a suitable instance of a subclass of the BaseAuth class. * `username` [string] Username to authenticate as. * `password` [string] Password to authenticate with. * `authoritative_source` [string] Authoritative source of the query. * `auth_options` [dict] A dict which, if authenticated as a trusted user, can override `username` and `authoritative_source`. """ if auth_options is None: auth_options = {} # validate arguments if (authoritative_source is None): raise AuthError("Missing authoritative_source.") # remove invalid cache entries rem = list() for key in self._auth_cache: if self._auth_cache[key]['valid_until'] < datetime.utcnow(): rem.append(key) for key in rem: del(self._auth_cache[key]) user_authbackend = username.rsplit('@', 1) # Find out what auth backend to use. # If no auth backend was specified in username, use default backend = "" if len(user_authbackend) == 1: backend = self._config.get('auth', 'default_backend') self._logger.debug("Using default auth backend %s" % backend) else: backend = user_authbackend[1] # do we have a cached instance? auth_str = ( str(username) + str(password) + str(authoritative_source) + str(auth_options) ) if auth_str in self._auth_cache: self._logger.debug('found cached auth object for user %s' % username) return self._auth_cache[auth_str]['auth_object'] # Create auth object try: auth = self._backends[backend](backend, user_authbackend[0], password, authoritative_source, auth_options) except KeyError: raise AuthError("Invalid auth backend '%s' specified" % str(backend)) # save auth object to cache self._auth_cache[auth_str] = { 'valid_until': datetime.utcnow() + timedelta(seconds=self._config.getint('auth', 'auth_cache_timeout')), 'auth_object': auth } return auth class BaseAuth: """ A base authentication class. All authentication modules should extend this class. """ username = None password = None authenticated_as = None full_name = None authoritative_source = None auth_backend = None trusted = None readonly = None _logger = None _auth_options = None _cfg = None def __init__(self, username, password, authoritative_source, auth_backend, auth_options=None): """ Constructor. Note that the instance variables not are set by the constructor but by the :func:`authenticate` method. Therefore, run the :func:`authenticate`-method before trying to access those variables! * `username` [string] Username to authenticate as. * `password` [string] Password to authenticate with. * `authoritative_source` [string] Authoritative source of the query. * `auth_backend` [string] Name of authentication backend. * `auth_options` [dict] A dict which, if authenticated as a trusted user, can override `username` and `authoritative_source`. """ if auth_options is None: auth_options = {} self._logger = logging.getLogger(self.__class__.__name__) self._cfg = NipapConfig() self.username = username self.password = password self.auth_backend = auth_backend self.authoritative_source = authoritative_source self._auth_options = auth_options def authenticate(self): """ Verify authentication. Returns True/False dependant on whether the authentication succeeded or not. """ return False def authorize(self): """ Verify authorization. Check if a user is authorized to perform a specific operation. """ return False class LdapAuth(BaseAuth): """ An authentication and authorization class for LDAP auth. """ _ldap_uri = None _ldap_basedn = None _ldap_binddn_fmt = None _ldap_search = None _ldap_search_binddn = None _ldap_search_password = None _ldap_rw_group = None _ldap_ro_group = None _ldap_conn = None _ldap_search_conn = None _authenticated = None def __init__(self, name, username, password, authoritative_source, auth_options=None): """ Constructor. Note that the instance variables not are set by the constructor but by the :func:`authenticate` method. Therefore, run the :func:`authenticate`-method before trying to access those variables! * `name` [string] Name of auth backend. * `username` [string] Username to authenticate as. * `password` [string] Password to authenticate with. * `authoritative_source` [string] Authoritative source of the query. * `auth_options` [dict] A dict which, if authenticated as a trusted user, can override `username` and `authoritative_source`. """ if auth_options is None: auth_options = {} BaseAuth.__init__(self, username, password, authoritative_source, name, auth_options) base_auth_backend = 'auth.backends.' + self.auth_backend self._ldap_uri = self._cfg.get(base_auth_backend, 'uri') self._ldap_basedn = self._cfg.get(base_auth_backend, 'basedn') self._ldap_binddn_fmt = self._cfg.get(base_auth_backend, 'binddn_fmt') self._ldap_search = self._cfg.get(base_auth_backend, 'search') self._ldap_tls = False if self._cfg.has_option(base_auth_backend, 'tls'): self._ldap_tls = self._cfg.getboolean(base_auth_backend, 'tls') self._ldap_ro_group = None self._ldap_rw_group = None if self._cfg.has_option(base_auth_backend, 'ro_group'): self._ldap_ro_group = self._cfg.get(base_auth_backend, 'ro_group') if self._cfg.has_option(base_auth_backend, 'rw_group'): self._ldap_rw_group = self._cfg.get(base_auth_backend, 'rw_group') self._logger.debug('Creating LdapAuth instance') if not ldap: self._logger.error('Unable to load Python ldap module, please verify it is installed') raise AuthError('Unable to authenticate') self._logger.debug('LDAP URI: ' + self._ldap_uri) self._ldap_conn = ldap.initialize(self._ldap_uri) # Shall we use a separate connection for search? if self._cfg.has_option(base_auth_backend, 'search_binddn'): self._ldap_search_binddn = self._cfg.get(base_auth_backend, 'search_binddn') self._ldap_search_password = self._cfg.get(base_auth_backend, 'search_password') self._ldap_search_conn = ldap.initialize(self._ldap_uri) if self._ldap_tls: try: self._ldap_conn.start_tls_s() if self._ldap_search_conn is not None: self._ldap_search_conn.start_tls_s() except (ldap.CONNECT_ERROR, ldap.SERVER_DOWN) as exc: self._logger.error('Attempted to start TLS with ldap server but failed.') self._logger.exception(exc) raise AuthError('Unable to establish secure connection to ldap server') def authenticate(self): """ Verify authentication. Returns True/False dependant on whether the authentication succeeded or not. """ # if authentication has been performed, return last result if self._authenticated is not None: return self._authenticated try: self._ldap_conn.simple_bind_s(self._ldap_binddn_fmt.format(ldap.dn.escape_dn_chars(self.username)), self.password) except ldap.SERVER_DOWN as exc: raise AuthError('Could not connect to LDAP server') except (ldap.INVALID_CREDENTIALS, ldap.INVALID_DN_SYNTAX, ldap.UNWILLING_TO_PERFORM) as exc: # Auth failed self._logger.debug('erroneous password for user %s' % self.username) self._authenticated = False return self._authenticated # auth succeeded self.authenticated_as = self.username self.trusted = False self.readonly = False try: # Create separate connection for search? if self._ldap_search_conn is not None: self._ldap_search_conn.simple_bind(self._ldap_search_binddn, self._ldap_search_password) search_conn = self._ldap_search_conn else: search_conn = self._ldap_conn res = search_conn.search_s(self._ldap_basedn, ldap.SCOPE_SUBTREE, self._ldap_search.format(ldap.dn.escape_dn_chars(self.username)), ['cn','memberOf']) if res[0][1]['cn'][0] is not None: self.full_name = res[0][1]['cn'][0].decode('utf-8') # check for ro_group membership if ro_group is configured if self._ldap_ro_group: if self._ldap_ro_group in res[0][1].get('memberOf', []): self.readonly = True # check for rw_group membership if rw_group is configured if self._ldap_rw_group: if self._ldap_rw_group in res[0][1].get('memberOf', []): self.readonly = False else: # if ro_group is configured, and the user is a member of # neither the ro_group nor the rw_group, fail authentication. if self._ldap_ro_group: if self._ldap_ro_group not in res[0][1].get('memberOf', []): self._authenticated = False return self._authenticated else: self.readonly = True except ldap.LDAPError as exc: raise AuthError(exc) except KeyError: raise AuthError('LDAP attribute missing') except IndexError: self.full_name = '' # authentication fails if either ro_group or rw_group are configured # and the user is not found. if self._ldap_rw_group or self._ldap_ro_group: self._authenticated = False return self._authenticated self._authenticated = True self._logger.debug('successfully authenticated as %s, username %s, full_name %s, readonly %s' % (self.authenticated_as, self.username, self.full_name, str(self.readonly))) return self._authenticated class SqliteAuth(BaseAuth): """ An authentication and authorization class for local auth. """ _db_conn = None _db_curs = None _authenticated = None def __init__(self, name, username, password, authoritative_source, auth_options=None): """ Constructor. Note that the instance variables not are set by the constructor but by the :func:`authenticate` method. Therefore, run the :func:`authenticate`-method before trying to access those variables! * `name` [string] Name of auth backend. * `username` [string] Username to authenticate as. * `password` [string] Password to authenticate with. * `authoritative_source` [string] Authoritative source of the query. * `auth_options` [dict] A dict which, if authenticated as a trusted user, can override `username` and `authoritative_source`. If the user database and tables are not found, they are created. """ if auth_options is None: auth_options = {} BaseAuth.__init__(self, username, password, authoritative_source, name, auth_options) self._logger.debug('Creating SqliteAuth instance') # connect to database try: self._db_conn = sqlite3.connect(self._cfg.get('auth.backends.' + self.auth_backend, 'db_path'), check_same_thread = False) self._db_conn.row_factory = sqlite3.Row self._db_curs = self._db_conn.cursor() except sqlite3.Error as exc: self._logger.error('Could not open user database: %s' % str(exc)) raise AuthError(str(exc)) def _latest_db_version(self): """ Check if database is of the latest version Fairly stupid functions that simply checks for existence of columns. """ # make sure that user table exists sql_verify_table = '''SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'user' ''' self._db_curs.execute(sql_verify_table) if len(self._db_curs.fetchall()) < 1: raise AuthSqliteError("No 'user' table.") for column in ('username', 'pwd_salt', 'pwd_hash', 'full_name', 'trusted', 'readonly'): sql = "SELECT %s FROM user" % column try: self._db_curs.execute(sql) except: return False return True def _create_database(self): """ Set up database Creates tables required for the authentication module. """ self._logger.info('creating user database') sql = '''CREATE TABLE IF NOT EXISTS user ( username NOT NULL PRIMARY KEY, pwd_salt NOT NULL, pwd_hash NOT NULL, full_name, trusted NOT NULL DEFAULT 0, readonly NOT NULL DEFAULT 0 )''' self._db_curs.execute(sql) self._db_conn.commit() def _upgrade_database(self): """ Upgrade database to latest version This is a fairly primitive function that won't look at how the database looks like but just blindly run commands. """ self._logger.info('upgrading user database') # add readonly column try: sql = '''ALTER TABLE user ADD COLUMN readonly NOT NULL DEFAULT 0''' self._db_curs.execute(sql) except: pass self._db_conn.commit() def authenticate(self): """ Verify authentication. Returns True/False dependant on whether the authentication succeeded or not. """ # if authentication has been performed, return last result if self._authenticated is not None: return self._authenticated self._logger.debug('Trying to authenticate as user \'%s\'' % self.username) user = self.get_user(self.username) # Was user found? if user is None: self._logger.debug('unknown user %s' % self.username) self._authenticated = False return self._authenticated # verify password if self._gen_hash(self.password, user['pwd_salt']) != user['pwd_hash']: # Auth failed self._logger.debug('erroneous password for user %s' % self.username) self._authenticated = False return self._authenticated # auth succeeded self.authenticated_as = self.username self._authenticated = True self.trusted = bool(user['trusted']) self.readonly = bool(user['readonly']) if self.trusted: # user can impersonate other users # this also means that a system and full_name can be specified if 'username' in self._auth_options: self.username = self._auth_options['username'] # TODO: b0rk out if full_name is supplied and username not? if 'full_name' in self._auth_options: self.full_name = self._auth_options['full_name'] if 'authoritative_source' in self._auth_options: self.authoritative_source = self._auth_options['authoritative_source'] if 'readonly' in self._auth_options: self.readonly = self._auth_options['readonly'] else: self.full_name = user['full_name'] self._logger.debug('successfully authenticated as %s, username %s, full_name %s, readonly %s' % (self.authenticated_as, self.username, self.full_name, str(self.readonly))) return self._authenticated def get_user(self, username): """ Fetch the user from the database The function will return None if the user is not found """ sql = '''SELECT * FROM user WHERE username = ?''' self._db_curs.execute(sql, (username, )) user = self._db_curs.fetchone() return user def add_user(self, username, password, full_name=None, trusted=False, readonly=False): """ Add user to SQLite database. * `username` [string] Username of new user. * `password` [string] Password of new user. * `full_name` [string] Full name of new user. * `trusted` [boolean] Whether the new user should be trusted or not. * `readonly` [boolean] Whether the new user can only read or not """ # generate salt char_set = string.ascii_letters + string.digits salt = ''.join(random.choice(char_set) for x in range(8)) sql = '''INSERT INTO user (username, pwd_salt, pwd_hash, full_name, trusted, readonly) VALUES (?, ?, ?, ?, ?, ?)''' try: self._db_curs.execute(sql, (username, salt, self._gen_hash(password, salt), full_name, trusted or False, readonly or False)) self._db_conn.commit() except (sqlite3.OperationalError, sqlite3.IntegrityError) as error: raise AuthError(error) def remove_user(self, username): """ Remove user from the SQLite database. * `username` [string] Username of user to remove. """ sql = '''DELETE FROM user WHERE username = ?''' try: self._db_curs.execute(sql, (username, )) self._db_conn.commit() except (sqlite3.OperationalError, sqlite3.IntegrityError) as error: raise AuthError(error) return self._db_curs.rowcount def modify_user(self, username, data): """ Modify user in SQLite database. Since username is used as primary key and we only have a single argument for it we can't modify the username right now. """ if 'password' in data: # generate salt char_set = string.ascii_letters + string.digits data['pwd_salt'] = ''.join(random.choice(char_set) for x in range(8)) data['pwd_hash'] = self._gen_hash(data['password'], data['pwd_salt']) del(data['password']) sql = "UPDATE user SET " sql += ', '.join("%s = ?" % k for k in sorted(data)) sql += " WHERE username = ?" vals = [] for k in sorted(data): vals.append(data[k]) vals.append(username) try: self._db_curs.execute(sql, vals) self._db_conn.commit() except (sqlite3.OperationalError, sqlite3.IntegrityError) as error: raise AuthError(error) def list_users(self): """ List all users. """ sql = "SELECT * FROM user ORDER BY username" self._db_curs.execute(sql) users = list() for row in self._db_curs: users.append(dict(row)) return users def _gen_hash(self, password, salt): """ Generate password hash. """ # generate hash h = hashlib.sha1() h.update(salt) h.update(password) return h.hexdigest() class AuthError(Exception): """ General auth exception. """ error_code = 1500 class AuthenticationFailed(AuthError): """ Authentication failed. """ error_code = 1510 class AuthorizationFailed(AuthError): """ Authorization failed. """ error_code = 1520 class AuthSqliteError(AuthError): """ Problem with the Sqlite database """
{ "repo_name": "SpriteLink/NIPAP", "path": "nipap/nipap/authlib.py", "copies": "4", "size": "25277", "license": "mit", "hash": -7644860344624668000, "line_mean": 33.1120107962, "line_max": 179, "alpha_frac": 0.5885192072, "autogenerated": false, "ratio": 4.435339533251447, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003134029892004937, "num_lines": 741 }
# authentication methods import os import hashlib import binascii from struct import pack try: from genelist import conf except: pass def authenticate(username, password): found_pass = None with conf.conn() as conn: cur = conn.cursor() cur.execute('SELECT id, password FROM users WHERE username = %s', (username,)) record = cur.fetchone() cur.close() if not record: return False userid = record[0] found_pass = record[1] method, val = found_pass.split("$", 1) if method == 'pbkdf2': salt, hashed_passwd = val.split('$', 1) # PBDKF2_HMAC, using the embedded salt dk = backported_pbkdf2_hmac('sha256', password, salt, 100000) if secure_compare(hashed_passwd, binascii.hexlify(dk)): return userid return None def generate_salt(n=16): rand_string = os.urandom(n) return binascii.hexlify(rand_string) def secure_compare(foo, bar): match = True for one, two in zip(foo, bar): if one != two: match = False return match #################################################################### # BACKPORTED From: Python 2.7.8 # See: https://pypi.python.org/pypi/backports.pbkdf2/0.1 #################################################################### _string_type = basestring _trans_5C = b''.join(chr(x ^ 0x5C) for x in xrange(256)) _trans_36 = b''.join(chr(x ^ 0x36) for x in xrange(256)) def _loop_counter(loop, pack=pack): return pack(b'>I', loop) # hack from django.utils.crypto def _from_bytes(value, endianess, int=int): return int(binascii.hexlify(value), 16) def _to_bytes(value, length, endianess): fmt = '%%0%ix' % (2 * length) return binascii.unhexlify(fmt % value) def backported_pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None): """ Password based key derivation function 2 (PKCS #5 v2.0) This Python implementations based on the hmac module about as fast as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and much faster for long passwords. Timings in seconds for pbkdf2_hmac('sha256', b'password10', b'salt', 50000) on an Intel I7 with 2.50 GHz: len(password) Python 3.3 OpenSSL 1.0.1e OpenSSL patched ------------- ---------- -------------- --------------- 10 0.408 0.431 0.233 100 0.418 0.509 0.228 500 0.433 1.01 0.230 1000 0.435 1.61 0.228 ------------- ---------- -------------- --------------- On Python 2.7 the code runs about 50% slower than on Python 3.3. """ if not isinstance(hash_name, _string_type): raise TypeError(hash_name) # no unicode, memoryview and other bytes-like objects are too hard to # support on 2.6 to 3.4 if not isinstance(password, (bytes, bytearray)): password = memoryview(str(password)).tobytes() if not isinstance(salt, (bytes, bytearray)): salt = memoryview(str(salt)).tobytes() # Fast inline HMAC implementation inner = hashlib.new(hash_name) outer = hashlib.new(hash_name) blocksize = getattr(inner, 'block_size', 64) if len(password) > blocksize: password = hashlib.new(hash_name, password).digest() password = password + b'\x00' * (blocksize - len(password)) inner.update(password.translate(_trans_36)) outer.update(password.translate(_trans_5C)) def prf(msg, inner=inner, outer=outer): # PBKDF2_HMAC uses the password as key. We can re-use the same # digest objects and and just update copies to skip initialization. icpy = inner.copy() ocpy = outer.copy() icpy.update(msg) ocpy.update(icpy.digest()) return ocpy.digest() if iterations < 1: raise ValueError(iterations) if dklen is None: dklen = outer.digest_size if dklen < 1: raise ValueError(dklen) from_bytes = _from_bytes to_bytes = _to_bytes loop_counter = _loop_counter dkey = b'' loop = 1 while len(dkey) < dklen: prev = prf(salt + loop_counter(loop)) # endianess doesn't matter here as long to / from use the same rkey = from_bytes(prev, 'big') for i in range(iterations - 1): prev = prf(prev) # rkey = rkey ^ prev rkey ^= from_bytes(prev, 'big') loop += 1 dkey += to_bytes(rkey, inner.digest_size, 'big') return dkey[:dklen] if __name__ == '__main__': import sys print "Username : %s" % sys.argv[1] salt = generate_salt() if len(sys.argv) < 3 else sys.argv[3] print "Password hash: 1;%s;%s" % (salt, binascii.hexlify(backported_pbkdf2_hmac('sha256', sys.argv[2], salt, 100000)))
{ "repo_name": "compgen-io/genelist", "path": "src/genelist/auth.py", "copies": "1", "size": "4819", "license": "bsd-3-clause", "hash": -3196120618602061000, "line_mean": 29.11875, "line_max": 122, "alpha_frac": 0.5789582901, "autogenerated": false, "ratio": 3.5749258160237387, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46538841061237385, "avg_score": null, "num_lines": null }
"""Authentication middleware""" from django.db.models import Q from django.http import HttpResponseForbidden from django.shortcuts import redirect from django.utils.deprecation import MiddlewareMixin from django.utils.http import urlquote from ipware import get_client_ip from rest_framework.permissions import SAFE_METHODS from social_core.exceptions import SocialAuthBaseException from social_django.middleware import SocialAuthExceptionMiddleware from authentication.models import BlockedIPRange class SocialAuthExceptionRedirectMiddleware(SocialAuthExceptionMiddleware): """ This middleware subclasses SocialAuthExceptionMiddleware and overrides process_exception to provide an implementation that does not use django.contrib.messages and instead only issues a redirect """ def process_exception(self, request, exception): """ Note: this is a subset of the SocialAuthExceptionMiddleware implementation """ strategy = getattr(request, "social_strategy", None) if strategy is None or self.raise_exception(request, exception): return if isinstance(exception, SocialAuthBaseException): backend = getattr(request, "backend", None) backend_name = getattr(backend, "name", "unknown-backend") message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) if url: url += ("?" in url and "&" or "?") + "message={0}&backend={1}".format( urlquote(message), backend_name ) return redirect(url) class BlockedIPMiddleware(MiddlewareMixin): """ Only allow GET/HEAD requests for blocked ips, unless exempt or a superuser """ def process_view(self, request, callback, callback_args, callback_kwargs): """ Blocks an individual request if: it is from a blocked ip range, routable, not a safe request and not from a superuser (don't want admins accidentally locking themselves out). Args: request (django.http.request.Request): the request to inspect """ if ( not getattr(callback, "blocked_ip_exempt", False) and not request.user.is_superuser and not request.path.startswith("/admin/") ): user_ip, is_routable = get_client_ip(request) if user_ip is None or ( is_routable and request.method not in SAFE_METHODS and BlockedIPRange.objects.filter( Q(ip_start__lte=user_ip) & Q(ip_end__gte=user_ip) ).count() > 0 ): return HttpResponseForbidden()
{ "repo_name": "mitodl/open-discussions", "path": "authentication/middleware.py", "copies": "1", "size": "2758", "license": "bsd-3-clause", "hash": -3173586217589866000, "line_mean": 36.2702702703, "line_max": 100, "alpha_frac": 0.6493836113, "autogenerated": false, "ratio": 4.666666666666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.000602088471010386, "num_lines": 74 }
"""Authentication middleware""" from django.shortcuts import redirect from django.utils.http import urlquote from social_core.exceptions import SocialAuthBaseException from social_django.middleware import SocialAuthExceptionMiddleware class SocialAuthExceptionRedirectMiddleware(SocialAuthExceptionMiddleware): """ This middleware subclasses SocialAuthExceptionMiddleware and overrides process_exception to provide an implementation that does not use django.contrib.messages and instead only issues a redirect """ def process_exception(self, request, exception): """ Note: this is a subset of the SocialAuthExceptionMiddleware implementation """ strategy = getattr(request, "social_strategy", None) if strategy is None or self.raise_exception(request, exception): return if isinstance(exception, SocialAuthBaseException): backend = getattr(request, "backend", None) backend_name = getattr(backend, "name", "unknown-backend") message = self.get_message(request, exception) url = self.get_redirect_uri(request, exception) if url: url += ("?" in url and "&" or "?") + "message={0}&backend={1}".format( urlquote(message), backend_name ) return redirect(url)
{ "repo_name": "mitodl/bootcamp-ecommerce", "path": "authentication/middleware.py", "copies": "1", "size": "1373", "license": "bsd-3-clause", "hash": -7086708821217838000, "line_mean": 38.2285714286, "line_max": 86, "alpha_frac": 0.6722505462, "autogenerated": false, "ratio": 4.9035714285714285, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6075821974771429, "avg_score": null, "num_lines": null }
"""Authentication module for registration, logging in, and changing password""" from flask import render_template, redirect, url_for, flash, \ request, session from flask_login import login_user, logout_user, current_user from app import app from .alchemy import db, User, tablename from passlib.hash import sha256_crypt import gc from os import mkdir from os.path import isdir from app.decorators import start_thread from .forms import RegistrationForm, ChangePwdForm, EnterEmail, ForgotPass import time import shutil from app import mail from flask_mail import Message @start_thread def setup_mail(msg): with app.app_context(): mail.send(msg) def send_mail(subject, sender, recipients, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.html = html_body setup_mail(msg) def registration(username, email, password, form): try: # set free account storage volume plan = 2000 # mbytes mb_left = 2000 dat = User.query.filter_by(username=username).first() dat_email = User.query.filter_by(email=email).first() if dat is not None: flash('Username not available.') return redirect(url_for('register', form=form)) elif dat_email is not None: flash('Email is already in use.') return redirect(url_for('register', form=form)) else: db.session.add(User(None, username, email, password, plan, mb_left, False)) user = User.query.filter_by(username=username).first() flash('Registration Successful.') login_user(user) next = request.args.get('next') main_path = app.config['USER_STORAGE_PATH'] user_path = main_path + str(user.username) # check if directory exists and create main user directory if isdir(user_path): shutil.rmtree(user_path) mkdir(user_path) # create users first folder in main directory mkdir(user_path + '/' + 'My Folder') # create personal user table in db class User_folder(db.Model): __tablename__ = str(user.username) id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(150)) code = db.Column(db.String(150)) path = db.Column(db.String(150)) date = db.Column(db.String(15)) size = db.Column(db.Float) db.create_all() path = user_path + '/' + 'My Folder' date = time.strftime("%d/%m/%Y") user_table = tablename(str(user.username)) data = user_table('My Folder', None, path, date, None) db.session.add(data) db.session.commit() gc.collect() return redirect(next or url_for('user_home')) except Exception as e: return redirect(url_for('register', error=str(e))) def log_in(user_submit, password): try: user = User.query.filter_by(username=user_submit).first() if user is None: flash('Invalid Credentials.') return redirect(url_for('login')) else: pwd = user.password if sha256_crypt.verify(password, pwd): login_user(user) flash('Hello, ' + user.username + '!') next = request.args.get('next') gc.collect() return redirect(next or url_for('user_home')) else: flash('Invalid Credentials.') return redirect(url_for('login')) except Exception as e: return redirect(url_for("login_page", error=(str(e)))) def change_pass(user, old_pwd, new_pwd): if sha256_crypt.verify(old_pwd, user.password): user.password = sha256_crypt.encrypt(new_pwd) db.session.commit() flash('Password Changed Successfully.') def forgot_password(): # set base url for email link url_main = app.config['RESET_PASS_URL'] form = EnterEmail(request.form) if request.method == "POST" and form.validate(): email = form.email.data usr = User.query.filter_by(email=email).first() # check if usr query has data if usr and usr.email == email: # generate token token = usr.get_token() # set url for email link url_token = url_main + token sender = app.config['MAIL_USERNAME'] subject = "Password Reset." recipients = [email] html_body = "<div class='container' align='middle'> \ <img src='http://<yourdomain>/static/images/<yourlogo>.jpg' \ style='width:30%; height:15%;'' alt='Brand Name'> \ </img> \ <p><b>You have requested to change your password.<br></p> \ Please click <a href=" + url_token + ">Here</a> \ </div>" send_mail(subject, sender, recipients, html_body) # set db entry to True to show token is unused usr.reset_pass = True db.session.commit() flash("An e-mail has been sent to your e-mail address.") return redirect(url_for('forgot_pwd')) else: flash("Invalid e-mail.") return redirect(url_for('forgot_pwd')) return render_template('forgot_password.html', form=form) def reset_password(token=None): form = ForgotPass(request.form) # verify the generated token usr = User.verify_token(token) # check if token is unused is_token_unused = usr.reset_pass if token and usr and is_token_unused: if form.validate(): # set db entry to false to mark token was used usr.reset_pass = False # set new password usr.password = sha256_crypt.encrypt(form.new_pwd.data) db.session.commit() flash('Password has been Successfully changed.') return redirect(url_for('login_page')) else: flash('Session expired.') return redirect(url_for('forgot_pwd')) return render_template('reset_password.html', form=form)
{ "repo_name": "disfear86/mushcloud", "path": "app/auth.py", "copies": "1", "size": "6298", "license": "apache-2.0", "hash": 2940657145644754400, "line_mean": 33.6043956044, "line_max": 87, "alpha_frac": 0.5770085742, "autogenerated": false, "ratio": 4.116339869281045, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5193348443481045, "avg_score": null, "num_lines": null }
"""Authentication operations.""" import logging import requests from objectrocket import bases from objectrocket import errors logger = logging.getLogger(__name__) class Auth(bases.BaseAuthLayer): """Authentication operations. :param objectrocket.client.Client base_client: An objectrocket.client.Client instance. """ def __init__(self, base_client): self.__username = None self.__password = None self.__token = None super(Auth, self).__init__(base_client=base_client) ##################### # Public interface. # ##################### def authenticate(self, username, password): """Authenticate against the ObjectRocket API. :param str username: The username to perform basic authentication against the API with. :param str password: The password to perform basic authentication against the API with. :returns: A token used for authentication against token protected resources. :rtype: str """ # Update the username and password bound to this instance for re-authentication needs. self._username = username self._password = password # Attempt to authenticate. resp = requests.get( self._url, auth=(username, password), **self._default_request_kwargs ) # Attempt to extract authentication data. try: if resp.status_code == 200: json_data = resp.json() token = json_data['data']['token'] elif resp.status_code == 401: raise errors.AuthFailure(resp.json().get('message', 'Authentication Failure.')) else: raise errors.AuthFailure( "Unknown exception while authenticating: '{}'".format(resp.text) ) except errors.AuthFailure: raise except Exception as ex: logging.exception(ex) raise errors.AuthFailure('{}: {}'.format(ex.__class__.__name__, ex)) # Update the token bound to this instance for use by other client operations layers. self._token = token logger.info('New API token received: "{}".'.format(token)) return token ###################### # Private interface. # ###################### @property def _default_request_kwargs(self): """The default request keyword arguments to be passed to the requests library.""" return super(Auth, self)._default_request_kwargs @property def _password(self): """The password currently being used for authentication.""" return self.__password @_password.setter def _password(self, new_password): """Update the password to be used for authentication.""" self.__password = new_password def _refresh(self): """Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use. """ # Request and set a new API token. new_token = self.authenticate(self._username, self._password) self._token = new_token logger.info('New API token received: "{}".'.format(new_token)) return self._token @property def _token(self): """The API token this instance is currently using.""" return self.__token @_token.setter def _token(self, new_token): """Update the API token which this instance is to use.""" self.__token = new_token return self.__token @property def _url(self): """The base URL for authentication operations.""" return self._client._url + 'tokens/' @property def _username(self): """The username currently being used for authentication.""" return self.__username @_username.setter def _username(self, new_username): """Update the username to be used for authentication.""" self.__username = new_username def _verify(self, token): """Verify that the given token is valid. :param str token: The API token to verify. :returns: The token's corresponding user model as a dict, or None if invalid. :rtype: dict """ # Attempt to authenticate. url = '{}{}/'.format(self._url, 'verify') resp = requests.post( url, json={'token': token}, **self._default_request_kwargs ) if resp.status_code == 200: return resp.json().get('data', None) return None
{ "repo_name": "objectrocket/python-client", "path": "objectrocket/auth.py", "copies": "1", "size": "4660", "license": "mit", "hash": -7697218388234832000, "line_mean": 32.2857142857, "line_max": 95, "alpha_frac": 0.5916309013, "autogenerated": false, "ratio": 4.844074844074844, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5935705745374844, "avg_score": null, "num_lines": null }
"""Authentication out of the box. References ---------- https://stackoverflow.com/questions/13428708/best-way-to-make-flask-logins-login-required-the-default https://stackoverflow.com/questions/14367991/flask-before-request-add-exception-for-specific-route """ from typing import Dict, Optional from abc import ABC, abstractmethod from flask import Response, request, session from bowtie._app import App class Auth(ABC): """Abstract Authentication class.""" def __init__(self, app: App) -> None: """Create Auth class to protect flask routes and socketio connect.""" self.app = app self.app.app.before_request(self.before_request) # only need to check credentials on "connect" event self.app._socketio.on('connect')(self.socketio_auth) # pylint: disable=protected-access @abstractmethod def before_request(self): """Determine if a user is allowed to view this route. Name is subject to change. Returns ------- None, if no protection is needed. """ @abstractmethod def socketio_auth(self) -> bool: """Determine if a user is allowed to establish socketio connection. Name is subject to change. """ class BasicAuth(Auth): """Basic Authentication.""" def __init__(self, app: App, credentials: Dict[str, str]) -> None: """ Create basic auth with credentials. Parameters ---------- credentials : dict Usernames and passwords should be passed in as a dictionary. Examples -------- >>> from bowtie import App >>> from bowtie.auth import BasicAuth >>> app = App(__name__) >>> auth = BasicAuth(app, {'alice': 'secret1', 'bob': 'secret2'}) """ self.credentials = credentials super().__init__(app) def _check_auth(self, username: str, password: str) -> bool: """Check if a username/password combination is valid.""" try: return self.credentials[username] == password except KeyError: return False def socketio_auth(self) -> bool: """Determine if a user is allowed to establish socketio connection.""" try: return session['logged_in'] in self.credentials except KeyError: return False def before_request(self) -> Optional[Response]: """Determine if a user is allowed to view this route.""" auth = request.authorization if not auth or not self._check_auth(auth.username, auth.password): return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'} ) session['logged_in'] = auth.username # pylint wants this return statement return None
{ "repo_name": "jwkvam/conex", "path": "bowtie/auth.py", "copies": "1", "size": "2953", "license": "mit", "hash": -7849294948340268000, "line_mean": 29.7604166667, "line_max": 101, "alpha_frac": 0.6088723332, "autogenerated": false, "ratio": 4.460725075528701, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.55695974087287, "avg_score": null, "num_lines": null }
# authentication_password.py is the first layer of Security Module. This system works with traditional user - password architecture. from Tkinter import * # destroys the authentication window def quit(self): self.root.destroy() def authentication_password_main(): root = Tk() root.geometry("500x200") root.wm_title("Authentication") ''' These lines for adding text area on top of the authentication UI T = Text(root, height=1, width=8) T.pack() T.insert(END, "your text") ''' username = "admin" password = "admin_123456" #that's the given password #username entry username_entry = Entry(root) username_entry.pack() #password entry password_entry = Entry(root, show='*') password_entry.pack() def trylogin(): #this method is called when the button is pressed #to get what's written inside the entries, I use get() #check if both username and password in the entry is same of the given ones if username == username_entry.get() and password == password_entry.get(): print("Login is successful!") root.quit() # Authentication is successfull #add your codes after this line for specifying what program does when login is successful else: print("Wrong") #when you press this button, trylogin is called button = Button(root, text="Login", command = trylogin) button.pack() #App starter root.mainloop() authentication_password_main()
{ "repo_name": "ahmetozlu/aipa", "path": "modules/#1 Security Module/#1.1 UserName - Password Authentication/authentication_password.py", "copies": "1", "size": "1394", "license": "mit", "hash": -1816965476439668500, "line_mean": 26.88, "line_max": 132, "alpha_frac": 0.7216642755, "autogenerated": false, "ratio": 3.6396866840731072, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48613509595731075, "avg_score": null, "num_lines": null }
"""Authentication plug-in for rights management.""" from lib.plugin import Plugin from lib.core import User from lib.logger import log from lib.config import configuration class AuthPlugin(Plugin): def __init__(self): Plugin.__init__(self, 'auth') self._set_summary(_('Authentification plugin')) self._add_command('auth', '<password>', _('Show that you are you by \ using your password from registration. Better do this using private \ adressing.')) self._add_command('register', '<password>', _('Registers your nick \ with password. Better do this using private adressing.')) self._add_command('set', '<user> <level>', _('Changes user\'s level \ to the indicated one, which can be an integer from 1 to 29.')) self._add_command('level', '[<user>]', _('Shows user\'s level, or \ yours if you specify no username.')) for user in User.users.values(): user.trusted = False def _private_only(self, msg): """Complains to the user and returns True if the given message was send in a query.""" if msg.chan != msg.bot.nickname: msg.bot.msg(msg.reply_to, msg.prefix + _('Please, tell me this in a private query.')) return True else: return False def auth(self, msg): """ If a user uses auth with the correct password he can use all possibilities of the level associated with his account. """ if self._private_only(msg): return False log('i', 'User attempting to authenticate: ' + str(msg.user)) if msg.params == msg.user.password: msg.user.trusted = True return msg.prefix + _("You're authenticated by now.") else: return msg.prefix + _("Passwords do NOT match. DO NOT TRY TO FOOL ME!") def register(self, msg): """ Enables a user to authenticate and therefore reach higher levels by assigning a password of his choice to his user object. """ if self._private_only(msg): return False log('i', 'User tries to register: ' + str(msg.user)) if msg.user.password is not None: return msg.prefix + _('Sorry! Your nick is already registered.') elif not msg.params: return msg.prefix + _('You have to specify a password.') else: msg.user.password = msg.params log('i', 'User %s registered with password %s.' % (msg.user.name, msg.user.password)) if msg.user.name.lower() == configuration.superadmin: msg.user.level = 30 else: msg.user.level = 0 msg.user.trusted = True User.users.sync() return msg.prefix + _('Your nick has been successfully registered!') def set(self, msg): """Sets level of a user to a certain value.""" token = msg.params.split() if len(token) == 2: level = int(token[1]) allowed = self.require_level(msg.user, level + 1) if allowed: if token[0] in User.users: old_level = User.users[token[0]].level or 0 User.users[token[0]].level = level User.users.sync() log('i', '%s changed the level of user %s from %d to %d.' % ( msg.user.name, token[0], old_level, level)) return msg.prefix + \ _('Changed the level of user %s from %d to %d.') % ( token[0], old_level, level) else: return msg.prefix + \ _('User %s is not registered.' % token[0]) else: return msg.prefix + \ _('Unauthorized. Level %d required.' % (level + 1)) else: return msg.prefix + \ _('You need to specify the username and the level.') def level(self, msg): """Tells which level the user you ask for has, or if you don't specify a user, which level you have and if you have already authentificated yourself for the current run or not.""" user = (msg.params.split() + [None])[0] if user and user != msg.user.name: if user in User.users: if User.users[user].password is not None: return msg.prefix + _('User %s has level %d.') % \ (user,User.users[user].level) else: return msg.prefix + _('User %s is not registered.') % user elif user == msg.bot.nickname: return msg.prefix + _('That\'s me, I have no level.') else: return msg.prefix + _('I\'ve never seen %s.') % user else: if msg.user.password is None: return msg.prefix + _('You are not registered.') levelstr = _('Your level is %d ') % msg.user.level if msg.user.trusted: return msg.prefix + levelstr + \ _('and you are authenticated.') else: return msg.prefix + levelstr + \ _('but you are currently not authenticated.') def __unauthenticate(self, user, bot): try: User.users[user].trusted = False except KeyError: User.users[user] = User(user, bot.factory.connection) def user_quit(self, bot, user, quitmsg): self.__unauthenticate(user, bot) def user_part(self, bot, user, chan, reason=None): self.__unauthenticate(user, bot) # def user_joined(self, bot, user, chan): # try_to_add_user(user) # # def user_kicked(self, bot, chan, kickee, kicker, message): # try_to_add_user(user) # # def user_action(self, bot, user, chan, data): # try_to_add_user(user) # # def user_part(self, bot, user, chan, reason=None): # try_to_add_user(user) def try_to_add_user(name): try: User.users[name] except KeyError: User.users[name] = User(name)
{ "repo_name": "AustrianGeekForce/p1tr-legacy", "path": "plugins/auth.py", "copies": "1", "size": "6271", "license": "bsd-3-clause", "hash": 3680356825581324300, "line_mean": 39.4580645161, "line_max": 83, "alpha_frac": 0.5321320364, "autogenerated": false, "ratio": 4.2115513767629285, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5243683413162928, "avg_score": null, "num_lines": null }
"""Authentication process""" import cherrypy import lib.db_users as db_users def check_auth(required=True, user_role=None): """Check authentication""" if required: user = db_users.user_by_session(cherrypy.session.id) if user == None: cherrypy.lib.sessions.expire() raise cherrypy.HTTPRedirect("/login") elif user_role != None and user['role'] != user_role: raise cherrypy.HTTPRedirect("/login") def check_rights(): """Check if the user has the right to visit a page""" try: temp = cherrypy.request.path_info.split("/")[2] except IndexError: raise cherrypy.HTTPRedirect("/") view_user = db_users.user_by_name(temp) if view_user == None: raise cherrypy.HTTPError(404, "Profile not found") elif view_user['privacy'] == 'private': user = db_users.user_by_session(cherrypy.session.id) if user == None or user['username'] != view_user['username']: raise cherrypy.HTTPError(404, "Profile not public")
{ "repo_name": "JB26/Bibthek", "path": "lib/auth.py", "copies": "1", "size": "1040", "license": "mit", "hash": 7636006552158591000, "line_mean": 37.5185185185, "line_max": 69, "alpha_frac": 0.6298076923, "autogenerated": false, "ratio": 3.9393939393939394, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5069201631693939, "avg_score": null, "num_lines": null }
"""Authentication related tests.""" import json import pytest from server.extensions import db from server.models.user import User @pytest.mark.usefixtures('dbmodels', 'dbtransaction') class TestUserCreation: """User creation tests.""" def test_user_creation(self, app, client): """A user an be created.""" data = { 'nickname': 'admin', 'email': 'admin@admin.de', 'password': 'hunter2', } response = client.post( '/api/user/register', data=json.dumps(data), content_type='application/json', ) assert response.status_code == 201 user = db.session.query(User) \ .filter(User.nickname == 'admin') \ .filter(User.email == 'admin@admin.de') \ .one_or_none() assert user assert user.verify_password('hunter2') assert not user.verify_password('hunter1337') def test_cant_reuse_credentials(self, app, client): """Credentials are unique.""" data = { 'nickname': 'admin', 'email': 'admin@admin.de', 'password': 'hunter2', } response = client.post( '/api/user/register', data=json.dumps(data), content_type='application/json', ) assert response.status_code == 201 response = client.post( '/api/user/register', data=json.dumps(data), content_type='application/json', ) assert response.status_code == 409 @pytest.mark.parametrize('email', ['test', 'test@de']) def test_invalid_email(self, app, client, email): """Can't use invalid emails.""" data = { 'nickname': 'test', 'email': email, 'password': 'testtest', } response = client.post( '/api/user/register', data=json.dumps(data), content_type='application/json', ) assert response.status_code == 422 @pytest.mark.usefixtures('dbmodels', 'dbtransaction') class TestAuthentication: """Authentication related tests.""" def test_login(self, app, client, user): """Login works with nickname and mail.""" for identifier in [user.nickname, user.email]: data = { 'identifier': identifier, 'password': 'hunter2', } response = client.post( '/api/auth/login', data=json.dumps(data), content_type='application/json', ) assert response.status_code == 200
{ "repo_name": "Nukesor/spacesurvival", "path": "tests/api/test_auth.py", "copies": "1", "size": "2598", "license": "mit", "hash": 5119047904296635000, "line_mean": 31.0740740741, "line_max": 58, "alpha_frac": 0.5473441109, "autogenerated": false, "ratio": 4.217532467532467, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 81 }
AUTHENTICATION_REQUIRED_401 = 401 NOT_AUTHORIZED_403 = 403 INVALID_REQUEST_400 = 400 REQUEST_ENTITY_TOO_LARGE_413 = 413 NOT_FOUND_404 = 404 INTERNAL_SERVER_ERROR_500 = 500 RESOURCE_CONFLICT_409 = 409 PAYMENT_REQUIRED_402 = 402 HEADER_PRECONDITIONS_FAILED = 412 LOCKED_423 = 423 TOO_MANY_REQUESTS_429 = 429 class JSONAPIException(Exception): status_code = INTERNAL_SERVER_ERROR_500 error_title = "Internal Error." error_type_ = None error_description = None @property def error_type(self): return self.error_type_ or type(self).__name__ def __init__(self, status_code=None, error_type=None, error_title=None, error_description=None): self.status_code = status_code or self.status_code self.error_title = error_title or self.error_title self.error_description = error_description or self.error_description or self.error_title self.error_type_ = error_type class ParameterMissing(JSONAPIException): status_code = INVALID_REQUEST_400 parameter_name = None def __init__(self, parameter_name=None): self.error_title = \ "Parameter '{}' is missing.".format(parameter_name or self.parameter_name) class ParameterInvalid(JSONAPIException): status_code = INVALID_REQUEST_400 def __init__(self, parameter_name, parameter_value): self.error_title = \ "Invalid value for parameter '{}'.".format(parameter_name) self.error_description = \ "Invalid parameter for '{0}': {1}.".format(parameter_name, parameter_value) class BadPageCountParameter(ParameterInvalid): def __init__(self, parameter_value): super().__init__(parameter_name='page[count]', parameter_value=parameter_value) self.error_description = "Page sizes must be integers." class BadPageCursorParameter(ParameterInvalid): def __init__(self, parameter_value): super().__init__(parameter_name='page[cursor]', parameter_value=parameter_value) self.error_description = "Provided cursor was not parsable." class BadPageOffsetParameter(ParameterInvalid): def __init__(self, parameter_value): super().__init__(parameter_name='page[offset]', parameter_value=parameter_value) self.error_description = "Page offsets must be integers." class DataMissing(ParameterMissing): parameter_name = 'data'
{ "repo_name": "Patreon/cartographer", "path": "cartographer/exceptions/request_exceptions.py", "copies": "1", "size": "2455", "license": "apache-2.0", "hash": -2017469020522481400, "line_mean": 32.6301369863, "line_max": 96, "alpha_frac": 0.6676171079, "autogenerated": false, "ratio": 3.9660743134087237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5133691421308724, "avg_score": null, "num_lines": null }
"""Authentication serializers""" import logging from django.contrib.auth import get_user_model from django.http import HttpResponseRedirect from social_django.views import _do_login as login from social_core.backends.email import EmailAuth from social_core.exceptions import InvalidEmail, AuthException from social_core.utils import ( user_is_authenticated, user_is_active, partial_pipeline_data, sanitize_redirect, ) from rest_framework import serializers from authentication.exceptions import ( InvalidPasswordException, RequirePasswordException, RequirePasswordAndPersonalInfoException, RequireProviderException, RequireRegistrationException, RequireProfileException, UserExportBlockedException, UserTryAgainLaterException, ) from authentication.utils import SocialAuthState from compliance.constants import REASON_CODES_RETRYABLE from profiles.serializers import UserSerializer PARTIAL_PIPELINE_TOKEN_KEY = "partial_pipeline_token" log = logging.getLogger() User = get_user_model() class SocialAuthSerializer(serializers.Serializer): """Serializer for social auth""" partial_token = serializers.CharField(source="get_partial_token", default=None) flow = serializers.ChoiceField( choices=( (SocialAuthState.FLOW_LOGIN, "Login"), (SocialAuthState.FLOW_REGISTER, "Register"), ) ) backend = serializers.CharField(read_only=True) state = serializers.CharField(read_only=True) errors = serializers.ListField(read_only=True) field_errors = serializers.DictField(read_only=True) redirect_url = serializers.CharField(read_only=True, default=None) extra_data = serializers.SerializerMethodField() def get_extra_data(self, instance): """Serialize extra_data""" if ( instance.user is not None and getattr(instance.user, "profile", None) is not None ): return {"name": instance.user.profile.name} return {} def _save_next(self, data): """Persists the next url to the session""" if "next" in data: backend = self.context["backend"] # Check and sanitize a user-defined GET/POST next field value redirect_uri = data["next"] if backend.setting("SANITIZE_REDIRECTS", True): allowed_hosts = backend.setting("ALLOWED_REDIRECT_HOSTS", []) + [ backend.strategy.request_host() ] redirect_uri = sanitize_redirect(allowed_hosts, redirect_uri) backend.strategy.session_set( "next", redirect_uri or backend.setting("LOGIN_REDIRECT_URL") ) def _authenticate(self, flow): """Authenticate the current request""" request = self.context["request"] strategy = self.context["strategy"] backend = self.context["backend"] user = request.user is_authenticated = user_is_authenticated(user) user = user if is_authenticated else None kwargs = {"request": request, "flow": flow} partial = partial_pipeline_data(backend, user, **kwargs) if partial: user = backend.continue_pipeline(partial) # clean partial data after usage strategy.clean_partial_pipeline(partial.token) else: user = backend.complete(user=user, **kwargs) # pop redirect value before the session is trashed on login(), but after # the pipeline so that the pipeline can change the redirect if needed redirect_url = backend.strategy.session_get("next", None) # check if the output value is something else than a user and just # return it to the client user_model = strategy.storage.user.user_model() if user and not isinstance(user, user_model): # this is where a redirect from the pipeline would get returned return user if is_authenticated: return SocialAuthState( SocialAuthState.STATE_SUCCESS, redirect_url=redirect_url ) elif user: if user_is_active(user): social_user = user.social_user login(backend, user, social_user) # store last login backend name in session strategy.session_set( "social_auth_last_login_backend", social_user.provider ) return SocialAuthState( SocialAuthState.STATE_SUCCESS, redirect_url=redirect_url ) else: return SocialAuthState(SocialAuthState.STATE_INACTIVE) else: # pragma: no cover # this follows similar code in PSA itself, but wasn't reachable through normal testing log.error("Unexpected authentication result") return SocialAuthState( SocialAuthState.STATE_ERROR, errors=["Unexpected authentication result"] ) def save(self, **kwargs): """'Save' the auth request""" try: result = super().save(**kwargs) except RequireProviderException as exc: result = SocialAuthState( SocialAuthState.STATE_LOGIN_BACKEND, backend=exc.social_auth.provider, user=exc.social_auth.user, ) except InvalidEmail: result = SocialAuthState(SocialAuthState.STATE_INVALID_EMAIL) except UserExportBlockedException as exc: next_state = ( SocialAuthState.STATE_ERROR_TEMPORARY if exc.reason_code in REASON_CODES_RETRYABLE else SocialAuthState.STATE_USER_BLOCKED ) result = SocialAuthState( next_state, partial=exc.partial, errors=[f"Error code: CS_{exc.reason_code}"], user=exc.user, ) except RequireProfileException as exc: result = SocialAuthState( SocialAuthState.STATE_REGISTER_EXTRA_DETAILS, partial=exc.partial ) except RequirePasswordAndPersonalInfoException as exc: result = SocialAuthState( SocialAuthState.STATE_REGISTER_DETAILS, partial=exc.partial ) except UserTryAgainLaterException as exc: result = SocialAuthState( SocialAuthState.STATE_ERROR_TEMPORARY, partial=exc.partial, errors=[f"Error code: CS_{exc.reason_code}"], user=exc.user, ) except AuthException as exc: log.exception("Received unexpected AuthException") result = SocialAuthState(SocialAuthState.STATE_ERROR, errors=[str(exc)]) if isinstance(result, SocialAuthState): if result.partial is not None: strategy = self.context["strategy"] strategy.storage.partial.store(result.partial) if result.state == SocialAuthState.STATE_REGISTER_CONFIRM_SENT: # If the user has just signed up and a verification link has been emailed, we need # to remove the partial token from the session. The partial token refers to a Partial # object, and we only want to continue the pipeline with that object if the user has # clicked the email verification link and the Partial has been matched from # the verification URL (that URL also contains the verification code, which we need # to continue the pipeline). self.context["backend"].strategy.session.pop(PARTIAL_PIPELINE_TOKEN_KEY) else: # if we got here, we saw an unexpected result log.error("Received unexpected result: %s", result) result = SocialAuthState(SocialAuthState.STATE_ERROR) # return the passed flow back to the caller # this way they know if they're on a particular page because of an attempted registration or login result.flow = self.validated_data["flow"] if result.backend is None: result.backend = self.context["backend"].name # update self.instance so we serialize the right object self.instance = result return result class LoginEmailSerializer(SocialAuthSerializer): """Serializer for email login""" partial_token = serializers.CharField( source="get_partial_token", read_only=True, default=None ) email = serializers.EmailField(write_only=True) next = serializers.CharField(write_only=True, required=False) def create(self, validated_data): """Try to 'save' the request""" self._save_next(validated_data) try: result = super()._authenticate(SocialAuthState.FLOW_LOGIN) except RequireRegistrationException: result = SocialAuthState( SocialAuthState.STATE_REGISTER_REQUIRED, field_errors={"email": "Couldn't find your account"}, ) except RequirePasswordException as exc: result = SocialAuthState( SocialAuthState.STATE_LOGIN_PASSWORD, partial=exc.partial, user=User.objects.filter( social_auth__uid=validated_data.get("email"), social_auth__provider=EmailAuth.name, ).first(), ) return result class LoginPasswordSerializer(SocialAuthSerializer): """Serializer for email login with password""" password = serializers.CharField(min_length=8, write_only=True) def create(self, validated_data): """Try to 'save' the request""" try: result = super()._authenticate(SocialAuthState.FLOW_LOGIN) except InvalidPasswordException as exc: result = SocialAuthState( SocialAuthState.STATE_ERROR, partial=exc.partial, field_errors={"password": str(exc)}, ) return result class RegisterEmailSerializer(SocialAuthSerializer): """Serializer for email register""" email = serializers.EmailField(write_only=True, required=False) next = serializers.CharField(write_only=True, required=False) def validate(self, attrs): token = (attrs.get("partial", {}) or {}).get("token", None) email = attrs.get("email", None) if not email and not token: raise serializers.ValidationError("One of 'partial' or 'email' is required") if email and token: raise serializers.ValidationError("Pass only one of 'partial' or 'email'") return attrs def create(self, validated_data): """Try to 'save' the request""" self._save_next(validated_data) try: result = super()._authenticate(SocialAuthState.FLOW_REGISTER) if isinstance(result, HttpResponseRedirect): # a redirect here means confirmation email sent result = SocialAuthState(SocialAuthState.STATE_REGISTER_CONFIRM_SENT) except RequirePasswordException as exc: result = SocialAuthState( SocialAuthState.STATE_LOGIN_PASSWORD, partial=exc.partial, errors=[str(exc)], ) return result class RegisterConfirmSerializer(SocialAuthSerializer): """Serializer for email confirmation""" partial_token = serializers.CharField(source="get_partial_token") verification_code = serializers.CharField(write_only=True) def create(self, validated_data): """Try to 'save' the request""" return super()._authenticate(SocialAuthState.FLOW_REGISTER) class RegisterDetailsSerializer(SocialAuthSerializer): """Serializer for registration details""" password = serializers.CharField(min_length=8, write_only=True) def create(self, validated_data): """Try to 'save' the request""" return super()._authenticate(SocialAuthState.FLOW_REGISTER) class RegisterComplianceSerializer(SocialAuthSerializer): """Serializer for registration compliance""" def get_extra_data(self, instance): """Serialize extra_data as a UserSerializer is user is not None""" if instance.user: return UserSerializer(instance.user).data return {} def create(self, validated_data): """Try to 'save' the request""" return super()._authenticate(SocialAuthState.FLOW_REGISTER) class RegisterExtraDetailsSerializer(SocialAuthSerializer): """Serializer for registration details""" gender = serializers.CharField(write_only=True) birth_year = serializers.CharField(write_only=True) company = serializers.CharField(write_only=True) job_title = serializers.CharField(write_only=True) industry = serializers.CharField(write_only=True, allow_blank=True, required=False) job_function = serializers.CharField( write_only=True, allow_blank=True, required=False ) years_experience = serializers.CharField( write_only=True, allow_blank=True, required=False ) company_size = serializers.CharField( write_only=True, allow_blank=True, required=False ) highest_education = serializers.CharField( write_only=True, allow_blank=True, required=False ) def create(self, validated_data): """Try to 'save' the request""" return super()._authenticate(SocialAuthState.FLOW_REGISTER)
{ "repo_name": "mitodl/bootcamp-ecommerce", "path": "authentication/serializers.py", "copies": "1", "size": "13551", "license": "bsd-3-clause", "hash": 2646002320414702000, "line_mean": 37.4971590909, "line_max": 106, "alpha_frac": 0.6366319829, "autogenerated": false, "ratio": 4.592002710945442, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005645492714885081, "num_lines": 352 }
"""AuthenticationsLog API Version 1.0. This API client was generated using a template. Make sure this code is valid before using it. """ import logging from datetime import date, datetime from .base import BaseCanvasAPI from .base import BaseModel class AuthenticationsLogAPI(BaseCanvasAPI): """AuthenticationsLog API Version 1.0.""" def __init__(self, *args, **kwargs): """Init method for AuthenticationsLogAPI.""" super(AuthenticationsLogAPI, self).__init__(*args, **kwargs) self.logger = logging.getLogger("py3canvas.AuthenticationsLogAPI") def query_by_login(self, login_id, end_time=None, start_time=None): """ Query by login. List authentication events for a given login. """ path = {} data = {} params = {} # REQUIRED - PATH - login_id """ID""" path["login_id"] = login_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: if issubclass(start_time.__class__, str): start_time = self._validate_iso8601_string(start_time) elif issubclass(start_time.__class__, date) or issubclass(start_time.__class__, datetime): start_time = start_time.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: if issubclass(end_time.__class__, str): end_time = self._validate_iso8601_string(end_time) elif issubclass(end_time.__class__, date) or issubclass(end_time.__class__, datetime): end_time = end_time.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/authentication/logins/{login_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/authentication/logins/{login_id}".format(**path), data=data, params=params, no_data=True) def query_by_account(self, account_id, end_time=None, start_time=None): """ Query by account. List authentication events for a given account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: if issubclass(start_time.__class__, str): start_time = self._validate_iso8601_string(start_time) elif issubclass(start_time.__class__, date) or issubclass(start_time.__class__, datetime): start_time = start_time.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: if issubclass(end_time.__class__, str): end_time = self._validate_iso8601_string(end_time) elif issubclass(end_time.__class__, date) or issubclass(end_time.__class__, datetime): end_time = end_time.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/authentication/accounts/{account_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/authentication/accounts/{account_id}".format(**path), data=data, params=params, no_data=True) def query_by_user(self, user_id, end_time=None, start_time=None): """ Query by user. List authentication events for a given user. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: if issubclass(start_time.__class__, str): start_time = self._validate_iso8601_string(start_time) elif issubclass(start_time.__class__, date) or issubclass(start_time.__class__, datetime): start_time = start_time.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: if issubclass(end_time.__class__, str): end_time = self._validate_iso8601_string(end_time) elif issubclass(end_time.__class__, date) or issubclass(end_time.__class__, datetime): end_time = end_time.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/authentication/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/authentication/users/{user_id}".format(**path), data=data, params=params, no_data=True) class Authenticationevent(BaseModel): """Authenticationevent Model.""" def __init__(self, pseudonym_id=None, created_at=None, user_id=None, event_type=None, account_id=None): """Init method for Authenticationevent class.""" self._pseudonym_id = pseudonym_id self._created_at = created_at self._user_id = user_id self._event_type = event_type self._account_id = account_id self.logger = logging.getLogger('py3canvas.Authenticationevent') @property def pseudonym_id(self): """ID of the pseudonym (login) associated with the event.""" return self._pseudonym_id @pseudonym_id.setter def pseudonym_id(self, value): """Setter for pseudonym_id property.""" self.logger.warn("Setting values on pseudonym_id will NOT update the remote Canvas instance.") self._pseudonym_id = value @property def created_at(self): """timestamp of the event.""" return self._created_at @created_at.setter def created_at(self, value): """Setter for created_at property.""" self.logger.warn("Setting values on created_at will NOT update the remote Canvas instance.") self._created_at = value @property def user_id(self): """ID of the user associated with the event will match the user_id in the associated pseudonym.""" return self._user_id @user_id.setter def user_id(self, value): """Setter for user_id property.""" self.logger.warn("Setting values on user_id will NOT update the remote Canvas instance.") self._user_id = value @property def event_type(self): """authentication event type ('login' or 'logout').""" return self._event_type @event_type.setter def event_type(self, value): """Setter for event_type property.""" self.logger.warn("Setting values on event_type will NOT update the remote Canvas instance.") self._event_type = value @property def account_id(self): """ID of the account associated with the event. will match the account_id in the associated pseudonym.""" return self._account_id @account_id.setter def account_id(self, value): """Setter for account_id property.""" self.logger.warn("Setting values on account_id will NOT update the remote Canvas instance.") self._account_id = value
{ "repo_name": "tylerclair/py3canvas", "path": "py3canvas/apis/authentications_log.py", "copies": "1", "size": "7828", "license": "mit", "hash": -8194398767201231000, "line_mean": 39.7708333333, "line_max": 174, "alpha_frac": 0.6067961165, "autogenerated": false, "ratio": 3.9022931206380855, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9978237030551488, "avg_score": 0.006170441317319545, "num_lines": 192 }
"""AuthenticationsLog API Version 1.0. This API client was generated using a template. Make sure this code is valid before using it. """ import logging from datetime import date, datetime from base import BaseCanvasAPI from base import BaseModel class AuthenticationsLogAPI(BaseCanvasAPI): """AuthenticationsLog API Version 1.0.""" def __init__(self, *args, **kwargs): """Init method for AuthenticationsLogAPI.""" super(AuthenticationsLogAPI, self).__init__(*args, **kwargs) self.logger = logging.getLogger("pycanvas.AuthenticationsLogAPI") def query_by_login(self, login_id, end_time=None, start_time=None): """ Query by login. List authentication events for a given login. """ path = {} data = {} params = {} # REQUIRED - PATH - login_id """ID""" path["login_id"] = login_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/authentication/logins/{login_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/authentication/logins/{login_id}".format(**path), data=data, params=params, no_data=True) def query_by_account(self, account_id, end_time=None, start_time=None): """ Query by account. List authentication events for a given account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/authentication/accounts/{account_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/authentication/accounts/{account_id}".format(**path), data=data, params=params, no_data=True) def query_by_user(self, user_id, end_time=None, start_time=None): """ Query by user. List authentication events for a given user. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/authentication/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/authentication/users/{user_id}".format(**path), data=data, params=params, no_data=True) class Authenticationevent(BaseModel): """Authenticationevent Model.""" def __init__(self, pseudonym_id=None, created_at=None, user_id=None, event_type=None, account_id=None): """Init method for Authenticationevent class.""" self._pseudonym_id = pseudonym_id self._created_at = created_at self._user_id = user_id self._event_type = event_type self._account_id = account_id self.logger = logging.getLogger('pycanvas.Authenticationevent') @property def pseudonym_id(self): """ID of the pseudonym (login) associated with the event.""" return self._pseudonym_id @pseudonym_id.setter def pseudonym_id(self, value): """Setter for pseudonym_id property.""" self.logger.warn("Setting values on pseudonym_id will NOT update the remote Canvas instance.") self._pseudonym_id = value @property def created_at(self): """timestamp of the event.""" return self._created_at @created_at.setter def created_at(self, value): """Setter for created_at property.""" self.logger.warn("Setting values on created_at will NOT update the remote Canvas instance.") self._created_at = value @property def user_id(self): """ID of the user associated with the event will match the user_id in the associated pseudonym.""" return self._user_id @user_id.setter def user_id(self, value): """Setter for user_id property.""" self.logger.warn("Setting values on user_id will NOT update the remote Canvas instance.") self._user_id = value @property def event_type(self): """authentication event type ('login' or 'logout').""" return self._event_type @event_type.setter def event_type(self, value): """Setter for event_type property.""" self.logger.warn("Setting values on event_type will NOT update the remote Canvas instance.") self._event_type = value @property def account_id(self): """ID of the account associated with the event. will match the account_id in the associated pseudonym.""" return self._account_id @account_id.setter def account_id(self, value): """Setter for account_id property.""" self.logger.warn("Setting values on account_id will NOT update the remote Canvas instance.") self._account_id = value
{ "repo_name": "PGower/PyCanvas", "path": "pycanvas/apis/authentications_log.py", "copies": "1", "size": "6210", "license": "mit", "hash": -8978200857455608000, "line_mean": 34.9642857143, "line_max": 174, "alpha_frac": 0.6022544283, "autogenerated": false, "ratio": 4.066797642436149, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003715547032022155, "num_lines": 168 }
# Authentication tests based on airmozilla # https://github.com/mozilla/airmozilla/blob/master/airmozilla/\ # auth/tests/test_views.py import base64 import json from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.test import RequestFactory from django.test.client import Client from django.test.utils import override_settings import mock from jinja2 import Markup from nose.exc import SkipTest from nose.tools import eq_, ok_ from test_utils import TestCase from remo.base import mozillians from remo.base.helpers import AES_PADDING, enc_string, mailhide, pad_string from remo.base.tests import (MozillianResponse, RemoTestCase, VOUCHED_MOZILLIAN, NOT_VOUCHED_MOZILLIAN, requires_login, requires_permission) from remo.base.tests.browserid_mock import mock_browserid from remo.base.views import robots_txt from remo.profiles.models import FunctionalArea from remo.profiles.tasks import check_mozillian_username from remo.profiles.tests import (FunctionalAreaFactory, UserFactory, UserStatusFactory) from remo.reports.models import Activity, Campaign from remo.reports.tests import ActivityFactory, CampaignFactory assert json.loads(VOUCHED_MOZILLIAN) assert json.loads(NOT_VOUCHED_MOZILLIAN) class MozilliansTest(TestCase): """Test Moziilians.""" @mock.patch('requests.get') def test_is_vouched(self, rget): """Test a user with vouched status""" def mocked_get(url, **options): if 'vouched' in url: return MozillianResponse(VOUCHED_MOZILLIAN) if 'not_vouched' in url: return MozillianResponse(NOT_VOUCHED_MOZILLIAN) if 'trouble' in url: return MozillianResponse('Failed', status_code=500) rget.side_effect = mocked_get ok_(mozillians.is_vouched('vouched@mail.com')) ok_(not mozillians.is_vouched('not_vouched@mail.com')) self.assertRaises( mozillians.BadStatusCodeError, mozillians.is_vouched, 'trouble@live.com') try: mozillians.is_vouched('trouble@live.com') raise except mozillians.BadStatusCodeError, msg: ok_(settings.MOZILLIANS_API_KEY not in str(msg)) @mock.patch('remo.profiles.tasks.is_vouched') def test_mozillian_username_exists(self, mocked_is_vouched): """Test that if an Anonymous Mozillians changes his settings in the mozillians.org, we update his username on our portal. """ mozillian = UserFactory.create(groups=['Mozillians']) mocked_is_vouched.return_value = {'is_vouched': True, 'email': mozillian.email, 'username': 'Mozillian', 'full_name': 'Awesome Mozillian'} check_mozillian_username.apply() user = User.objects.get(email=mozillian.email) eq_(user.userprofile.mozillian_username, u'Mozillian') eq_(user.get_full_name(), u'Awesome Mozillian') @mock.patch('remo.profiles.tasks.is_vouched') def test_mozillian_username_missing(self, mocked_is_vouched): """Test that if a Mozillian changes his settings in the mozillians.org, we update his username on our portal. """ mozillian = UserFactory.create( groups=['Mozillians'], first_name='Awesome', last_name='Mozillian', userprofile__mozillian_username='Mozillian') mocked_is_vouched.return_value = {'is_vouched': True, 'email': mozillian.email} check_mozillian_username.apply() user = User.objects.get(email=mozillian.email) eq_(user.userprofile.mozillian_username, '') eq_(user.get_full_name(), u'Anonymous Mozillian') class ViewsTest(TestCase): """Test views.""" fixtures = ['demo_users.json'] def setUp(self): self.settings_data = {'receive_email_on_add_comment': True} self.user_edit_settings_url = reverse('edit_settings') def _login_attempt(self, email, assertion='assertion123', next=None): if not next: next = '/' with mock_browserid(email): post_data = {'assertion': assertion, 'next': next} return self.client.post('/browserid/login/', post_data) def test_bad_verification(self): """Bad verification -> failure.""" response = self._login_attempt(None) eq_(response['content-type'], 'application/json') redirect = json.loads(response.content)['redirect'] eq_(redirect, settings.LOGIN_REDIRECT_URL_FAILURE) def test_invalid_login(self): """Bad BrowserID form - no assertion -> failure.""" response = self._login_attempt(None, None) eq_(response['content-type'], 'application/json') redirect = json.loads(response.content)['redirect'] eq_(redirect, settings.LOGIN_REDIRECT_URL_FAILURE) def test_is_vouched(self): """Login with vouched email.""" response = self._login_attempt('vouched@mail.com') eq_(response.status_code, 200) ok_(reverse('dashboard')) def test_view_main_page(self): """Get main page.""" c = Client() response = c.get(reverse('main')) eq_(response.status_code, 200) self.assertTemplateUsed(response, 'main.html') def test_view_about_page(self): """Get about page.""" c = Client() response = c.get(reverse('about')) eq_(response.status_code, 200) self.assertTemplateUsed(response, 'about.html') def test_view_faq_page(self): """Get faq page.""" c = Client() response = c.get(reverse('faq')) eq_(response.status_code, 200) self.assertTemplateUsed(response, 'faq.html') def test_mailhide_encryption(self): """Test email encryption function.""" if (getattr(settings, 'MAILHIDE_PUB_KEY', None) != '01Ni54q--g1yltekhaSmPYHQ=='): raise SkipTest('Skipping test due to different MailHide pub key.') test_strings = [('foo@example.com', '3m5HgumLI4YSLSY-YP9HQA=='), ('bar@example.net', '9o38o8PEvGrP6V5HSDg_FA=='), ('test@mozilla.org', ('ABBkk5Aj2-PJ_izt9yU8pMzt' 'wm-96eABHLBt8jRXxak='))] for string, encstring in test_strings: padded_string = pad_string(string, AES_PADDING) enced_string = enc_string(padded_string) safe_string = base64.urlsafe_b64encode(enced_string) eq_(encstring, safe_string) def test_mailhide_helper(self): """Test mailhide helper.""" if (getattr(settings, 'MAILHIDE_PUB_KEY', None) != '01Ni54q--g1yltekhaSmPYHQ=='): raise SkipTest('Skipping test due to different MailHide pub key.') m1 = Markup(u'<a href="http://mailhide.recaptcha.net/d?k=01Ni54q--g1yl' 'tekhaSmPYHQ==&c=3m5HgumLI4YSLSY-YP9HQA==" onclick="window' '.open(\'http://mailhide.recaptcha.net/d?k=01Ni54q--g1ylte' 'khaSmPYHQ==&c=3m5HgumLI4YSLSY-YP9HQA==\', \'\', \'toolbar' '=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizabl' 'e=0,width=500,height=300\'); return false;" title="Reveal' ' this e-mail address">f...@example.com</a>') m2 = Markup(u'<a href="http://mailhide.recaptcha.net/d?k=01Ni54q--g1yl' 'tekhaSmPYHQ==&c=9o38o8PEvGrP6V5HSDg_FA==" onclick="window' '.open(\'http://mailhide.recaptcha.net/d?k=01Ni54q--g1ylte' 'khaSmPYHQ==&c=9o38o8PEvGrP6V5HSDg_FA==\', \'\', \'toolbar' '=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizabl' 'e=0,width=500,height=300\'); return false;" title="Reveal' ' this e-mail address">b...@example.net</a>') m3 = Markup(u'<a href="http://mailhide.recaptcha.net/d?k=01Ni54q--g1yl' 'tekhaSmPYHQ==&c=ABBkk5Aj2-PJ_izt9yU8pMztwm-96eABHLBt8jRXx' 'ak=" onclick="window.open(\'http://mailhide.recaptcha.net' '/d?k=01Ni54q--g1yltekhaSmPYHQ==&c=ABBkk5Aj2-PJ_izt9yU8pMz' 'twm-96eABHLBt8jRXxak=\', \'\', \'toolbar=0,scrollbars=0,l' 'ocation=0,statusbar=0,menubar=0,resizable=0,width=500,hei' 'ght=300\'); return false;" title="Reveal this e-mail addr' 'ess">t...@mozilla.org</a>') test_strings = [('foo@example.com', m1), ('bar@example.net', m2), ('test@mozilla.org', m3)] for string, markup in test_strings: eq_(mailhide(string), markup) @override_settings(ENGAGE_ROBOTS=True) def test_robots_allowed(self): """Test robots.txt generation when crawling allowed.""" # Include a user who's not Rep UserFactory.create(userprofile__display_name='foo', groups=['Mozillian']) factory = RequestFactory() request = factory.get('/robots.txt') response = robots_txt(request) eq_(response.content, ('User-agent: *\nDisallow: /reports/\nDisallow: /u/md/r/\n' 'Disallow: /u/koki/r/\nDisallow: /u/koufos/r/\n' 'Disallow: /u/js/r/\n')) @override_settings(ENGAGE_ROBOTS=False) def test_robots_disallowed(self): """Test robots.txt generation when crawling disallowed.""" factory = RequestFactory() request = factory.get('/robots.txt') response = robots_txt(request) eq_(response.content, 'User-agent: *\nDisallow: /\n') def test_view_edit_settings_page(self): """Get edit settings page.""" c = Client() c.login(username='mentor', password='passwd') response = c.get(self.user_edit_settings_url) self.assertTemplateUsed(response, 'settings.html') def test_edit_settings_rep(self): """Test correct edit settings mail preferences as rep.""" c = Client() c.login(username='rep', password='passwd') response = c.post(self.user_edit_settings_url, self.settings_data, follow=True) eq_(response.request['PATH_INFO'], reverse('dashboard')) # Ensure that settings data were saved user = User.objects.get(username='rep') eq_(user.userprofile.receive_email_on_add_comment, self.settings_data['receive_email_on_add_comment']) class TestContribute(RemoTestCase): def test_base(self): response = self.client.get('/contribute.json') eq_(response.status_code, 200) # should be valid JSON ok_(json.loads(response.content)) eq_(response['Content-Type'], 'application/json') class EditUserStatusTests(RemoTestCase): """Tests related to the User status edit View.""" @requires_login() def test_get_as_anonymous(self): mentor = UserFactory.create() user = UserFactory.create(userprofile__mentor=mentor) display_name = user.userprofile.display_name UserStatusFactory.create(user=user) client = Client() client.get(reverse('edit_availability', kwargs={'display_name': display_name})) def test_get_as_owner(self): mentor = UserFactory.create() user = UserFactory.create(userprofile__mentor=mentor) display_name = user.userprofile.display_name UserStatusFactory.create(user=user) url = reverse('edit_availability', kwargs={'display_name': display_name}) self.get(url=url, user=user) self.assertTemplateUsed('edit_availability.html') @requires_permission() def test_get_as_other_rep(self): mentor = UserFactory.create() user = UserFactory.create(userprofile__mentor=mentor) rep = UserFactory.create() display_name = user.userprofile.display_name UserStatusFactory.create(user=user) url = reverse('edit_availability', kwargs={'display_name': display_name}) self.get(url=url, user=rep) @mock.patch('remo.base.views.messages.success') @mock.patch('remo.base.views.redirect', wraps=redirect) @mock.patch('remo.base.views.UserStatusForm') def test_add_unavailability_status(self, form_mock, redirect_mock, messages_mock): form_mock.is_valid.return_value = True user = UserFactory.create() display_name = user.userprofile.display_name response = self.post(url=reverse('edit_availability', kwargs={ 'display_name': display_name}), user=user) eq_(response.status_code, 200) messages_mock.assert_called_with( mock.ANY, 'Request submitted successfully.') redirect_mock.assert_called_with('dashboard') ok_(form_mock().save.called) class BaseListViewTest(RemoTestCase): """Test generic BaseListView class.""" def test_base_content_activities_list(self): """Test list activities.""" admin = UserFactory.create(groups=['Admin']) response = self.get(reverse('list_activities'), user=admin, follow=True) eq_(response.status_code, 200) eq_(response.context['verbose_name'], 'activity') eq_(response.context['verbose_name_plural'], 'activities') eq_(response.context['create_object_url'], reverse('create_activity')) self.assertTemplateUsed(response, 'base_content_list.html') def test_base_content_campaigns_list(self): """Test list campaigns.""" admin = UserFactory.create(groups=['Admin']) response = self.get(reverse('list_campaigns'), user=admin, follow=True) eq_(response.status_code, 200) eq_(response.context['verbose_name'], 'initiative') eq_(response.context['verbose_name_plural'], 'initiatives') eq_(response.context['create_object_url'], reverse('create_campaign')) self.assertTemplateUsed(response, 'base_content_list.html') def test_base_content_functional_areas_list(self): """Test list functional areas.""" admin = UserFactory.create(groups=['Admin']) response = self.get(reverse('list_functional_areas'), user=admin, follow=True) eq_(response.status_code, 200) eq_(response.context['verbose_name'], 'functional area') eq_(response.context['verbose_name_plural'], 'functional areas') eq_(response.context['create_object_url'], reverse('create_functional_area')) self.assertTemplateUsed(response, 'base_content_list.html') @requires_permission() def test_base_content_list_unauthed(self): """Test list base content unauthorized.""" user = UserFactory.create(groups=['Rep']) self.get(reverse('list_activities'), user=user, follow=True) class BaseCreateViewTest(RemoTestCase): """Test generic BaseCreateView class.""" def test_base_content_activity_create_get(self): """Test get create activity.""" admin = UserFactory.create(groups=['Admin']) response = self.get(reverse('create_activity'), user=admin, follow=True) eq_(response.status_code, 200) eq_(response.context['verbose_name'], 'activity') eq_(response.context['creating'], True) self.assertTemplateUsed(response, 'base_content_edit.html') def test_base_content_campaign_create_get(self): """Test get create campaign.""" admin = UserFactory.create(groups=['Admin']) response = self.get(reverse('create_campaign'), user=admin, follow=True) eq_(response.status_code, 200) eq_(response.context['verbose_name'], 'initiative') eq_(response.context['creating'], True) self.assertTemplateUsed(response, 'base_content_edit.html') def test_base_content_functional_area_create_get(self): """Test get create functional area.""" admin = UserFactory.create(groups=['Admin']) response = self.get(reverse('create_functional_area'), user=admin, follow=True) eq_(response.status_code, 200) eq_(response.context['verbose_name'], 'functional area') eq_(response.context['creating'], True) self.assertTemplateUsed(response, 'base_content_edit.html') def test_base_content_activity_create_post(self): """Test post create activity.""" admin = UserFactory.create(groups=['Admin']) response = self.post(reverse('create_activity'), user=admin, data={'name': 'test activity'}, follow=True) eq_(response.status_code, 200) query = Activity.objects.filter(name='test activity') eq_(query.exists(), True) def test_base_content_campaign_create_post(self): """Test post create campaign.""" admin = UserFactory.create(groups=['Admin']) response = self.post(reverse('create_campaign'), data={'name': 'test campaign'}, user=admin, follow=True) eq_(response.status_code, 200) query = Campaign.objects.filter(name='test campaign') eq_(query.exists(), True) def test_base_content_functional_area_create_post(self): """Test post create functional area.""" admin = UserFactory.create(groups=['Admin']) response = self.post(reverse('create_functional_area'), data={'name': 'test functional area'}, user=admin, follow=True) eq_(response.status_code, 200) query = FunctionalArea.objects.filter(name='test functional area') eq_(query.exists(), True) @requires_permission() def test_base_content_create_unauthed(self): """Test create base content unauthorized.""" user = UserFactory.create(groups=['Rep']) self.post(reverse('create_functional_area'), data={'name': 'test functional area'}, user=user, follow=True) class BaseUpdateViewTest(RemoTestCase): """Test generic BaseUpdateView class.""" def test_base_content_activity_edit_post(self): """Test post edit activity.""" admin = UserFactory.create(groups=['Admin']) activity = ActivityFactory.create(name='test activity') response = self.post(reverse('edit_activity', kwargs={'pk': activity.id}), user=admin, data={'name': 'edit activity'}, follow=True) eq_(response.status_code, 200) query = Activity.objects.filter(name='edit activity') eq_(query.exists(), True) def test_base_content_campaign_edit_post(self): """Test post edit campaign.""" admin = UserFactory.create(groups=['Admin']) campaign = CampaignFactory.create(name='test campaign') response = self.post(reverse('edit_campaign', kwargs={'pk': campaign.id}), data={'name': 'edit campaign'}, user=admin, follow=True) eq_(response.status_code, 200) query = Campaign.objects.filter(name='edit campaign') eq_(query.exists(), True) def test_base_content_functional_area_edit_post(self): """Test post edit functional area.""" admin = UserFactory.create(groups=['Admin']) area = FunctionalAreaFactory.create(name='test functional area') response = self.post(reverse('edit_functional_area', kwargs={'pk': area.id}), data={'name': 'edit functional area'}, user=admin, follow=True) eq_(response.status_code, 200) query = FunctionalArea.objects.filter(name='edit functional area') eq_(query.exists(), True) @requires_permission() def test_base_content_update_unauthed(self): """Test update base content unauthorized.""" user = UserFactory.create(groups=['Rep']) campaign = CampaignFactory.create(name='test campaign') self.post(reverse('edit_campaign', kwargs={'pk': campaign.id}), data={'name': 'edit campaign'}, user=user, follow=True)
{ "repo_name": "chirilo/remo", "path": "remo/base/tests/test_views.py", "copies": "3", "size": "20998", "license": "bsd-3-clause", "hash": 738716113425263600, "line_mean": 42.1170431211, "line_max": 79, "alpha_frac": 0.6002952662, "autogenerated": false, "ratio": 3.8748846650673556, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5975179931267356, "avg_score": null, "num_lines": null }
"""Authentication utils""" from social_core.utils import get_strategy from social_django.models import UserSocialAuth from social_django.utils import STORAGE from authentication.backends.micromasters import MicroMastersAuth from authentication.exceptions import UserMissingSocialAuthException # static for now ALLOWED_PROVIDERS = [MicroMastersAuth.name] class SocialAuthState: """Social auth state""" FLOW_REGISTER = "register" FLOW_LOGIN = "login" # login states STATE_LOGIN_EMAIL = "login/email" STATE_LOGIN_PASSWORD = "login/password" STATE_LOGIN_PROVIDER = "login/provider" # registration states STATE_REGISTER_EMAIL = "register/email" STATE_REGISTER_CONFIRM_SENT = "register/confirm-sent" STATE_REGISTER_CONFIRM = "register/confirm" STATE_REGISTER_DETAILS = "register/details" # end states STATE_SUCCESS = "success" STATE_ERROR = "error" STATE_INACTIVE = "inactive" STATE_INVALID_EMAIL = "invalid-email" def __init__( self, state, *, provider=None, partial=None, flow=None, errors=None, redirect_url=None, profile=None, ): # pylint: disable=too-many-arguments self.state = state self.partial = partial self.flow = flow self.provider = provider self.errors = errors or [] self.redirect_url = redirect_url self.profile = profile def get_partial_token(self): """Return the partial token or None""" return self.partial.token if self.partial else None def load_drf_strategy(request=None): """Returns the DRF strategy""" return get_strategy( "authentication.strategy.DjangoRestFrameworkStrategy", STORAGE, request ) def jwt_get_username_from_payload_handler(payload): """ Get the username from the payload To do this in concert with PSA, we lookup the username of the user that corresponds to the matching provider Args: payload(dict): JWT payload deserialized Returns: str: the username associated with this JWT """ username = payload.get("username") # if an provider is provided and valid, treat the username as a social auth username # otherwise the username is used verbatim for backwards compatibility provider = payload.get("provider") if provider and provider in ALLOWED_PROVIDERS: # get the User.username for this social auth # if this errors, (not exactly one UserSocialAuth/User) we want to know try: username = UserSocialAuth.objects.values_list( "user__username", flat=True ).get(provider=provider, uid=username) except UserSocialAuth.DoesNotExist as exc: raise UserMissingSocialAuthException( "Found no UserSocialAuth for username" ) from exc return username
{ "repo_name": "mitodl/open-discussions", "path": "authentication/utils.py", "copies": "1", "size": "2911", "license": "bsd-3-clause", "hash": -5809767254463715000, "line_mean": 29.3229166667, "line_max": 112, "alpha_frac": 0.6684987977, "autogenerated": false, "ratio": 4.255847953216374, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00020922408935732987, "num_lines": 96 }
"""Authentication utils""" from social_core.utils import get_strategy from social_django.utils import STORAGE class SocialAuthState: # pylint: disable=too-many-instance-attributes """Social auth state""" FLOW_REGISTER = "register" FLOW_LOGIN = "login" # login states STATE_LOGIN_EMAIL = "login/email" STATE_LOGIN_PASSWORD = "login/password" STATE_LOGIN_BACKEND = "login/backend" # registration states STATE_REGISTER_EMAIL = "register/email" STATE_REGISTER_CONFIRM_SENT = "register/confirm-sent" STATE_REGISTER_CONFIRM = "register/confirm" STATE_REGISTER_DETAILS = "register/details" STATE_REGISTER_EXTRA_DETAILS = "register/extra" STATE_REGISTER_REQUIRED = "register/required" STATE_ERROR_TEMPORARY = "register/retry" # end states STATE_SUCCESS = "success" STATE_ERROR = "error" STATE_INACTIVE = "inactive" STATE_INVALID_EMAIL = "invalid-email" STATE_USER_BLOCKED = "user-blocked" def __init__( self, state, *, backend=None, partial=None, flow=None, errors=None, field_errors=None, redirect_url=None, user=None, ): # pylint: disable=too-many-arguments self.state = state self.partial = partial self.flow = flow self.backend = backend self.errors = errors or [] self.field_errors = field_errors or {} self.redirect_url = redirect_url self.user = user def get_partial_token(self): """Return the partial token or None""" return self.partial.token if self.partial else None def load_drf_strategy(request=None): """Returns the DRF strategy""" return get_strategy( "authentication.strategy.DjangoRestFrameworkStrategy", STORAGE, request )
{ "repo_name": "mitodl/bootcamp-ecommerce", "path": "authentication/utils.py", "copies": "1", "size": "1821", "license": "bsd-3-clause", "hash": -5212208765886409000, "line_mean": 27.9047619048, "line_max": 79, "alpha_frac": 0.6436024163, "autogenerated": false, "ratio": 3.88272921108742, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.502633162738742, "avg_score": null, "num_lines": null }
"""Authentication views""" from urllib.parse import quote import requests from django.conf import settings from django.core import mail as django_mail from django.contrib.auth import get_user_model from django.shortcuts import render from social_core.backends.email import EmailAuth from social_django.models import UserSocialAuth from social_django.utils import load_backend from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from anymail.message import AnymailMessage from djoser.views import UserViewSet from djoser.utils import ActionViewMixin from djoser.email import PasswordResetEmail as DjoserPasswordResetEmail from authentication.serializers import ( LoginEmailSerializer, LoginPasswordSerializer, RegisterEmailSerializer, RegisterConfirmSerializer, RegisterDetailsSerializer, RegisterExtraDetailsSerializer, RegisterComplianceSerializer, ) from authentication.utils import load_drf_strategy from mail.v2.api import render_email_templates, send_messages User = get_user_model() class SocialAuthAPIView(APIView): """API view for social auth endpoints""" authentication_classes = [] permission_classes = [] def get_serializer_cls(self): # pragma: no cover """Return the serializer cls""" raise NotImplementedError("get_serializer_cls must be implemented") def post(self, request, backend_name=EmailAuth.name): """Processes a request""" if request.session.get("is_hijacked_user", False): return Response(status=status.HTTP_403_FORBIDDEN) serializer_cls = self.get_serializer_cls() strategy = load_drf_strategy(request) backend = load_backend(strategy, backend_name, None) serializer = serializer_cls( data=request.data, context={"request": request, "strategy": strategy, "backend": backend}, ) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LoginEmailView(SocialAuthAPIView): """Email login view""" def get_serializer_cls(self): """Return the serializer cls""" return LoginEmailSerializer class LoginPasswordView(SocialAuthAPIView): """Email login view""" def get_serializer_cls(self): """Return the serializer cls""" return LoginPasswordSerializer class RegisterEmailView(SocialAuthAPIView): """Email register view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterEmailSerializer def post(self, request, backend_name=EmailAuth.name): """ Verify recaptcha response before proceeding """ if request.session.get("is_hijacked_user", False): return Response(status=status.HTTP_403_FORBIDDEN) if settings.RECAPTCHA_SITE_KEY: r = requests.post( "https://www.google.com/recaptcha/api/siteverify?secret={key}&response={captcha}".format( key=quote(settings.RECAPTCHA_SECRET_KEY), captcha=quote(request.data["recaptcha"]), ) ) response = r.json() if not response["success"]: return Response(response, status=status.HTTP_400_BAD_REQUEST) return super().post(request, backend_name=backend_name) class RegisterConfirmView(SocialAuthAPIView): """Email registration confirmation view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterConfirmSerializer class RegisterDetailsView(SocialAuthAPIView): """Email registration details view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterDetailsSerializer class RegisterComplianceView(SocialAuthAPIView): """Email registration compliance details view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterComplianceSerializer class RegisterExtraDetailsView(SocialAuthAPIView): """Email registration extra details view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterExtraDetailsSerializer @api_view(["GET"]) @permission_classes([IsAuthenticated]) def get_social_auth_types(request): """ View that returns a serialized list of the logged-in user's UserSocialAuth types """ social_auths = ( UserSocialAuth.objects.filter(user=request.user).values("provider").distinct() ) return Response(data=social_auths, status=status.HTTP_200_OK) def confirmation_sent(request, **kwargs): # pylint: disable=unused-argument """The confirmation of an email being sent""" return render(request, "confirmation_sent.html") class CustomPasswordResetEmail(DjoserPasswordResetEmail): """Custom class to modify base functionality in Djoser's PasswordResetEmail class""" def send(self, to, *args, **kwargs): """ Overrides djoser.email.PasswordResetEmail#send to use our mail API. """ context = self.get_context_data() context.update(self.context) with django_mail.get_connection( settings.NOTIFICATION_EMAIL_BACKEND ) as connection: subject, text_body, html_body = render_email_templates( "password_reset", context ) msg = AnymailMessage( subject=subject, body=text_body, to=to, from_email=settings.MAILGUN_FROM_EMAIL, connection=connection, headers={"Reply-To": settings.BOOTCAMP_REPLY_TO_ADDRESS}, ) msg.attach_alternative(html_body, "text/html") send_messages([msg]) def get_context_data(self): """Adds base_url to the template context""" context = super().get_context_data() context["base_url"] = settings.SITE_BASE_URL return context class CustomDjoserAPIView(UserViewSet, ActionViewMixin): """ Custom view to modify base functionality in Djoser's UserViewSet class """
{ "repo_name": "mitodl/bootcamp-ecommerce", "path": "authentication/views.py", "copies": "1", "size": "6374", "license": "bsd-3-clause", "hash": -6791200546418788000, "line_mean": 32.3717277487, "line_max": 105, "alpha_frac": 0.6810480075, "autogenerated": false, "ratio": 4.404975812024879, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5586023819524879, "avg_score": null, "num_lines": null }
"""Authentication views""" from urllib.parse import quote import requests from django.conf import settings from django.core import mail as django_mail from django.contrib.auth import get_user_model, update_session_auth_hash from django.shortcuts import render, redirect from social_core.backends.email import EmailAuth from social_django.models import UserSocialAuth from social_django.utils import load_backend from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes, action from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.settings import api_settings from anymail.message import AnymailMessage from djoser.views import UserViewSet from djoser.utils import ActionViewMixin from djoser.email import PasswordResetEmail as DjoserPasswordResetEmail from authentication.serializers import ( LoginEmailSerializer, LoginPasswordSerializer, RegisterEmailSerializer, RegisterConfirmSerializer, RegisterDetailsSerializer, ) from authentication.utils import load_drf_strategy from mail.api import render_email_templates, send_messages User = get_user_model() class SocialAuthAPIView(APIView): """API view for social auth endpoints""" authentication_classes = [] permission_classes = [] def get_serializer_cls(self): # pragma: no cover """Return the serializer cls""" raise NotImplementedError("get_serializer_cls must be implemented") def post(self, request): """Processes a request""" if request.session.get("is_hijacked_user", False): return Response(status=status.HTTP_403_FORBIDDEN) serializer_cls = self.get_serializer_cls() strategy = load_drf_strategy(request) backend = load_backend(strategy, EmailAuth.name, None) serializer = serializer_cls( data=request.data, context={"request": request, "strategy": strategy, "backend": backend}, ) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LoginEmailView(SocialAuthAPIView): """Email login view""" def get_serializer_cls(self): """Return the serializer cls""" return LoginEmailSerializer class LoginPasswordView(SocialAuthAPIView): """Email login view""" def get_serializer_cls(self): """Return the serializer cls""" return LoginPasswordSerializer class RegisterEmailView(SocialAuthAPIView): """Email register view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterEmailSerializer def post(self, request): """ Verify recaptcha response before proceeding """ if request.session.get("is_hijacked_user", False): return Response(status=status.HTTP_403_FORBIDDEN) if settings.RECAPTCHA_SITE_KEY: r = requests.post( "https://www.google.com/recaptcha/api/siteverify?secret={key}&response={captcha}".format( key=quote(settings.RECAPTCHA_SECRET_KEY), captcha=quote(request.data["recaptcha"]), ) ) response = r.json() if not response["success"]: return Response(response, status=status.HTTP_400_BAD_REQUEST) return super().post(request) class RegisterConfirmView(SocialAuthAPIView): """Email registration confirmation view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterConfirmSerializer class RegisterDetailsView(SocialAuthAPIView): """Email registration details view""" def get_serializer_cls(self): """Return the serializer cls""" return RegisterDetailsSerializer @api_view(["GET"]) @permission_classes([IsAuthenticated]) def get_social_auth_types(request): """ View that returns a serialized list of the logged-in user's UserSocialAuth types """ social_auths = ( UserSocialAuth.objects.filter(user=request.user).values("provider").distinct() ) return Response(data=social_auths, status=status.HTTP_200_OK) def login_complete(request, **kwargs): # pylint: disable=unused-argument """View that completes the login""" # redirect to home response = redirect("/") if request.session.get("is_hijacked_user", False): return response if api_settings.JWT_AUTH_COOKIE in request.COOKIES: # to clear a cookie, it's most reliable to set it to expire immediately response.set_cookie( api_settings.JWT_AUTH_COOKIE, domain=settings.OPEN_DISCUSSIONS_COOKIE_DOMAIN, httponly=True, max_age=0, ) return response def confirmation_sent(request, **kwargs): # pylint: disable=unused-argument """The confirmation of an email being sent""" return render(request, "confirmation_sent.html") class CustomPasswordResetEmail(DjoserPasswordResetEmail): """Custom class to modify base functionality in Djoser's PasswordResetEmail class""" def send(self, to, *args, **kwargs): """ Overrides djoser.email.PasswordResetEmail#send to use our mail API. """ context = self.get_context_data() context.update(self.context) with django_mail.get_connection( settings.NOTIFICATION_EMAIL_BACKEND ) as connection: subject, text_body, html_body = render_email_templates( "password_reset", context ) msg = AnymailMessage( subject=subject, body=text_body, to=to, from_email=settings.MAILGUN_FROM_EMAIL, connection=connection, ) msg.attach_alternative(html_body, "text/html") send_messages([msg]) def get_context_data(self): """Adds base_url to the template context""" context = super().get_context_data() context["base_url"] = settings.SITE_BASE_URL return context class CustomDjoserAPIView(UserViewSet, ActionViewMixin): """ Overrides post methods of a Djoser view and adds one extra piece of logic: In version 0.30.0, the fetch function in redux-hammock does not handle responses with empty response data. Djoser returns 204's with empty response data, so we are coercing that to a 200 with an empty dict as the response data. This can be removed when redux-hammock is changed to support 204's. """ def post( self, request, **kwargs ): # pylint: disable=missing-docstring,arguments-differ response = super().post(request) if response.status_code == status.HTTP_204_NO_CONTENT: return Response({}, status=status.HTTP_200_OK) return response @action(["post"], detail=False) def reset_password(self, request, *args, **kwargs): response = super().reset_password(request, *args, **kwargs) # See class docstring for explanation if response.status_code == status.HTTP_204_NO_CONTENT: return Response({}, status=status.HTTP_200_OK) return response @action(["post"], detail=False) def reset_password_confirm(self, request, *args, **kwargs): response = super().reset_password_confirm(request, *args, **kwargs) # See class docstring for explanation if response.status_code == status.HTTP_204_NO_CONTENT: return Response({}, status=status.HTTP_200_OK) return response @action(["post"], detail=False) def set_password(self, request, *args, **kwargs): """ Overrides CustomDjoserAPIView.post to update the session after a successful password change. Without this explicit refresh, the user's session would be invalid and they would be logged out. """ response = super().set_password(request, *args, **kwargs) if response.status_code in (status.HTTP_200_OK, status.HTTP_204_NO_CONTENT): update_session_auth_hash(self.request, self.request.user) return Response({}, status=status.HTTP_200_OK) return response
{ "repo_name": "mitodl/open-discussions", "path": "authentication/views.py", "copies": "1", "size": "8358", "license": "bsd-3-clause", "hash": -8758623401227280000, "line_mean": 34.8712446352, "line_max": 105, "alpha_frac": 0.6689399378, "autogenerated": false, "ratio": 4.281762295081967, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5450702232881968, "avg_score": null, "num_lines": null }
# authentication/views.py # Create your views here. from django.views.decorators.csrf import csrf_protect from django.shortcuts import render_to_response from django.shortcuts import render from django.http import HttpResponseRedirect from django.template import RequestContext from authentication.models import User from authentication.utils.forms import RegistrationForm, UserProfileForm, UserCreationForm from django.contrib.auth.decorators import login_required from django.db import transaction from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.shortcuts import redirect @csrf_protect def register(request): form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( email=form.cleaned_data['email'], password=form.cleaned_data['password1'], first_name=form.cleaned_data['firstname'], last_name=form.cleaned_data['lastname'] ) return HttpResponseRedirect('/authentication/register/success/') # else: # form = RegistrationForm() # variables = RequestContext(request, { # 'form': form # }) context = { 'form': form } return render(request, 'registration/registration_form.html', context) # return render_to_response( # 'registration/registration_form.html', # variables, # ) def register_success(request): return render_to_response( 'registration/registration_success.html', ) @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = UserCreationForm(request.POST, instance=request.user) user_profile_form = UserProfileForm( request.POST, instance=request.user.user_profile) if user_form.is_valid() and user_profile_form.is_valid(): user_form.save() user_profile_form.save() messages.success(request, _( 'Your profile was successfully updated!')) return redirect('settings:profile') else: messages.error(request, _('Please correct the error below.')) else: user_form = UserCreationForm(instance=request.user) user_profile_form = UserProfileForm(instance=request.user.user_profile) return render(request, 'profile/user_profile.html', { 'user_form': user_form, 'user_profile_form': user_profile_form })
{ "repo_name": "midhun3112/restaurant_locator", "path": "Restaurant_Finder_App/restaurant_finder_app/restaurant_finder_app/authentication/utils/views.py", "copies": "1", "size": "2572", "license": "apache-2.0", "hash": -5951359536418152000, "line_mean": 32.8421052632, "line_max": 90, "alpha_frac": 0.6730171073, "autogenerated": false, "ratio": 4.344594594594595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5517611701894595, "avg_score": null, "num_lines": null }
# Auther: Alan from PIL import Image import numpy as np def test1(): input_path = "./laska.png" maxsize = (32, 32) # box = (0, 0, 28, 28) lena = Image.open(input_path) # print(type(lena)) lena.thumbnail(maxsize, Image.ANTIALIAS) lena.save("temp.jpg", "JPEG") # lena = Image.open("temp.jpg").crop(box) minsize = (224, 224) input_path = "./temp.jpg" lena = Image.open(input_path) # print(type(lena)) # lena.thumbnail(minsize, Image.ANTIALIAS) lena.resize(minsize, Image.ANTIALIAS).save("temp.png") # lena.save("temp.png", "PNG") def test2(): # input_path = "./temp.jpg" # lena = Image.open(input_path) # print((np.array(lena)).shape) # print(np.array(lena)) # batch = np.reshape(lena, [-1]) # print(batch[0:10]) # # ans = [] # for j in range(3): # for k in range(7): # # print(j, k, len(ans)) # for i in range(32): # t = batch[i * 32 + j * 1024:(i + 1) * 32 + j * 1024] # t = list(t) # ans.extend(t * 7) # 扩充7倍刚好 new_img = Image.new('RGB', (224, 224), 255) x = 0 for i in range(7): y = 0 for j in range(7): img = Image.open("./temp.jpg") width, height = img.size new_img.paste(img, (x, y)) y += height x += 32 # lena = Image.fromarray(np.reshape(ans, [224,224,3])) new_img.save("test2.png") if __name__ == "__main__": test2()
{ "repo_name": "songjs1993/DeepLearning", "path": "3CNN/vgg/analysis_classification.py", "copies": "1", "size": "1519", "license": "apache-2.0", "hash": -8476503702593357000, "line_mean": 23.737704918, "line_max": 70, "alpha_frac": 0.5049701789, "autogenerated": false, "ratio": 2.8364661654135337, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38414363443135335, "avg_score": null, "num_lines": null }
# Auther: Alan import matplotlib.pyplot as plt def draw_flower(): accu = [0.617647, 0.608824, 0.591176, 0.55, 0.561765] accu = [0.570588, 0.585294, 0.579412, 0.535294, 0.520588] # plt.plot([accu[0]] * M, label="base learner") plt.margins(0.08) plt.plot(accu, label="my") names = [0.2, 0.4, 0.6, 0.8, 1.0] plt.xticks(range(len(names)), names, rotation=45) plt.xlabel("Keep dropout") plt.ylabel("Accuracy rate (%)") # plt.title("CNN LeNet 5 (28*28)") plt.title("CNN LeNet 5 (26*26)") plt.ylim(0.5, 0.7) plt.show() def draw_cifar(): acc = [ 0.3481 , 0.3493 , 0.3392 , 0.3325 , 0.3159] # plt.plot([accu[0]] * M, label="base learner") plt.margins(0.08) plt.plot(acc, label="my") names = [0.2, 0.4, 0.6, 0.8, 1.0] plt.xticks(range(len(names)), names, rotation=45) plt.xlabel("Keep dropout") plt.ylabel("Accuracy rate (%)") # plt.title("CNN LeNet 5 (28*28)") plt.title("CNN LeNet 5") plt.ylim(0.3, 0.4) plt.show() if __name__=='__main__': draw_cifar()
{ "repo_name": "songjs1993/DeepLearning", "path": "3CNN/draw.py", "copies": "1", "size": "1057", "license": "apache-2.0", "hash": 610517153889668000, "line_mean": 26.1025641026, "line_max": 61, "alpha_frac": 0.5714285714, "autogenerated": false, "ratio": 2.4524361948955917, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3523864766295592, "avg_score": null, "num_lines": null }
# Auther: Alan import tensorflow as tf import random import os import scipy.io as sio import matplotlib.pyplot as plt # plt 用于显示图片 import matplotlib.image as mpimg # mpimg 用于读取图片 import numpy as np # import Image from PIL import Image global max_row, max_col def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): # 这里完全可以用一个数组代替 tf.zeros(units[1]) initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): # strides表示每一维度的步长 return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME") def max_pool_2x2(x): # ksize表示池化窗口的大小, 其中最前面的1和最后的1分别表示batch和channel(这里不考虑对不同batch做池化,所以设置为1) # 另外一个任务:判断两张图片是否为同一个人,觉得可以将其当做不同channel,一起进行池化的操作 return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME") def max_pool_3x3(x): return tf.nn.max_pool(x, ksize=[1,3,3,1], strides=[1,3,3,1], padding="SAME") def max_pool_5x5(x): return tf.nn.max_pool(x, ksize=[1,5,5,1], strides=[1,5,5,1], padding="SAME") def CNN_LeNet_5_Mnist(logs_path): """ LeNet对Mnist数据集进行测试 :return: """ from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # print(mnist) x = tf.placeholder(tf.float32, [None, 784]) y_ = tf.placeholder(tf.float32, [None, 10]) x_image = tf.reshape(x, [-1,28,28,1]) # 把向量重新整理成矩阵,最后一个表示通道个数 # 第一二参数值得卷积核尺寸大小,即patch,第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) # 多通道卷积,卷积出64个特征 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7*7*64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # train_step = tf.train.GradientDescentOptimizer(1e-2).minimize(cross_entropy) tf.summary.scalar("cross_entropy", cross_entropy) correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) merged_summary_op = tf.summary.merge_all() # 初始化变量 init_op = tf.global_variables_initializer() # 开始训练 sess = tf.Session() sess.run(init_op) # iterate # Xtrain, ytrain = get_batch(self.args, self.simrank, self.walks, minibatch * 100, self.tem_simrank) # 找一个大点的数据集测试效果 summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph()) # for i in range((int)(20000)): num_examples = 128*10 #这里暂时手动设置吧 minibatch = 128 for epoch in range(20): print("iter:", epoch) avg_cost = 0. total_batch = int(num_examples / minibatch) # Loop over all batches for i in range(total_batch): batchs = mnist.train.next_batch(minibatch) batch_xs, batch_ys = batchs[0], batchs[1] # batch_xs, batch_ys = next_batch(self.args, self.simrank, self.walks, minibatch, self.tem_simrank, # num_examples) # and summary nodes _, c, summary = sess.run([train_step, cross_entropy, merged_summary_op], feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}) # Write logs at every iteration summary_writer.add_summary(summary, epoch * total_batch + i) # Compute average loss avg_cost += c / total_batch if (i % 1 == 0): print("i:", i, " current c:", c, " ave_cost:", avg_cost) # Display logs per epoch step # if (epoch + 1) % display_step == 0: print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) # 到达一定程度进行测试test输出 if epoch%1==0: batchs = mnist.train.next_batch(minibatch) print("test accuracy %g" % sess.run(accuracy, feed_dict={ x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) # x: batchs[0], y_: batchs[1], keep_prob: 1.0})) def get_one_hot(label, num): y = [] for i in range(num): # 一共17个类别 if i == label: y.append(1.0) else: y.append(0.0) return y def read_data_flower(input_path, split_path): """ 获取train/val/test数据集 :param input_path: :param split_path: :return: """ splits = sio.loadmat(split_path) train_location = splits["trn1"][0] val_location = splits["val1"][0] # print("length of val_location: ",len(val_location)) test_location = splits["tst1"][0] # print(test_location[0]) with open(input_path+"/files.txt","r") as f: files = f.readlines() # 读取train_set trainX,valX,testX = [],[],[] trainY, valY, testY = [], [], [] maxsize = (28, 28) box = (0,0,28,28) # maxsize = (56, 56) # box = (0, 0, 56, 56) for train in train_location: lena = Image.open(input_path + files[int(train) - 1][:-1]) # print(type(lena)) lena.thumbnail(maxsize, Image.ANTIALIAS) lena.save("temp.jpg", "JPEG") lena = Image.open("temp.jpg").crop(box) # return np.array(trainX), np.array(trainY), np.array(valX), np.array(valY), np.array(testX), np.array(testY) trainX.append(np.reshape(lena, [-1])/255.0) # region = region.transpose(Image.ROTATE_180) # lena = mpimg.imread(input_path + files[int(train)-1][:-1]) # trainX.append(reshape(lena, max_row, max_col)) # print(lena[0][0],lena.shape) # print(type(lena)) # one-hot编码 label = int(float(train) / 80.001) trainY.append(get_one_hot(label, 17)) for val in val_location: lena = Image.open(input_path + files[int(val) - 1][:-1]) lena.thumbnail(maxsize, Image.ANTIALIAS) lena.save("temp.jpg", "JPEG") lena = Image.open("temp.jpg").crop(box) valX.append(np.reshape(lena, [-1])/255.0) # valX.append(np.reshape(lena, [lena.shape[0] * lena.shape[1] * lena.shape[2]])) label = int(float(val) / 80.001) valY.append(get_one_hot(label, 17)) for test in test_location: lena = Image.open(input_path + files[int(test) - 1][:-1]) lena.thumbnail(maxsize, Image.ANTIALIAS) lena.save("temp.jpg", "JPEG") lena = Image.open("temp.jpg").crop(box) testX.append(np.reshape(lena, [-1])/255.0) # testX.append(np.reshape(lena, [lena.shape[0] * lena.shape[1] * lena.shape[2]])) label = int(float(test) / 80.001) testY.append(get_one_hot(label, 17)) # Y改成one-hot编码 print("read data finish!") return np.array(trainX), np.array(trainY), np.array(valX), np.array(valY), np.array(testX), np.array(testY) def CNN_LeNet_5_56(input_path, split_path, logs_path): # LeNet_5的卷积网络,对花分类的数据集进行测试 (500, 541, 3) # read_data_flower(input_path, split_path) trainX, trainY, valX, valY, testX, testY = read_data_flower(input_path, split_path) print("trainX.shape: ",trainX.shape, trainY.shape, valX.shape, valY.shape, testX.shape, testY.shape) # 构建网络 x = tf.placeholder(tf.float32, [None, 784*3*4]) y_ = tf.placeholder(tf.float32, [None, 17]) x_image = tf.reshape(x, [-1,56,56,3]) # 把向量重新整理成矩阵,最后一个表示通道个数 # 第一二参数值得卷积核尺寸大小,即patch,第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征 W_conv1 = weight_variable([5, 5, 3, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) # 多通道卷积,卷积出64个特征 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([14*14*64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 14*14*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 17]) b_fc2 = bias_variable([17]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv+1e-10), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # train_step = tf.train.GradientDescentOptimizer(1e-2).minimize(cross_entropy) # tf.summary.scalar("cross_entropy", cross_entropy) correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # merged_summary_op = tf.summary.merge_all() # 初始化变量 init_op = tf.global_variables_initializer() # summary_writer = tf.summary.FileWriter(log_path, graph=tf.get_default_graph()) # 开始训练 drops = [1.0, 0.8, 0.6, 0.4, 0.2] for i in range(len(drops)): drop = drops[i] log_path = logs_path + str(i) print("log_path: ", log_path, " drop:", drop) sess = tf.Session() sess.run(init_op) # iterate # Xtrain, ytrain = get_batch(self.args, self.simrank, self.walks, minibatch * 100, self.tem_simrank) # 找一个大点的数据集测试效果 # for i in range((int)(20000)): num_examples = trainX.shape[0] minibatch = 16 maxc = -1.0 for epoch in range(1000): # for epoch in range(1): print("iter:", epoch) avg_cost = 0.0 total_batch = int(num_examples / minibatch) # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = next_batch(trainX, trainY, minibatch, num_examples) # print(type(batch_xs),type(batch_ys)) # print(batch_xs.shape, batch_ys.shape) # print(batch_xs[0]) # and summary nodes # print(sess.run(h_pool4, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # print(sess.run(y_conv, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # print(sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # return # print("batch_xs.shape: ", batch_xs.shape) # _, c, summary = sess.run([train_step, cross_entropy, merged_summary_op],feed_dict={x: batch_xs, y_: batch_ys, keep_prob: drop}) _, c = sess.run([train_step, cross_entropy], feed_dict={x: batch_xs, y_: batch_ys, keep_prob: drop}) # Write logs at every iteration # summary_writer.add_summary(summary, epoch * total_batch + i) # Compute average loss avg_cost += c / total_batch if (i % 1 == 0): print("i:", i, " current c:", c, " ave_cost:", avg_cost) # if i%1==0: # # print("valX.shape:", valX.shape, " valY.shape: ",valY.shape) # print("i: %d val accuracy %g" % (i, sess.run(accuracy, feed_dict={ # x: valX[0:10], y_: valY[0:10], keep_prob: 1.0}))) # print("i: %d test accuracy %g" % (i,sess.run(accuracy, feed_dict={ # x: testX, y_: testY, keep_prob: 1.0}))) # Display logs per epoch step # if (epoch + 1) % display_step == 0: print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) # 到达一定程度进行测试test输出 if epoch % 1 == 0: # batchs = mnist.train.next_batch(minibatch) acc = sess.run(accuracy, feed_dict={ x: testX, y_: testY, keep_prob: 1.0}) if acc > maxc: maxc = acc print("test accuracy %g" % acc) # x: batchs[0], y_: batchs[1], keep_prob: 1.0})) print("====================================================================") sess.close() print("maxc: ", maxc) print("finish!\n") def CNN_LeNet_5_28(input_path, split_path, logs_path): # read_data_flower(input_path, split_path) trainX, trainY, valX, valY, testX, testY = read_data_flower(input_path, split_path) print("trainX.shape: ",trainX.shape, trainY.shape, valX.shape, valY.shape, testX.shape, testY.shape) # 构建网络 x = tf.placeholder(tf.float32, [None, 784*3]) y_ = tf.placeholder(tf.float32, [None, 17]) x_image = tf.reshape(x, [-1,28,28,3]) # 把向量重新整理成矩阵,最后一个表示通道个数 # 第一二参数值得卷积核尺寸大小,即patch,第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征 W_conv1 = weight_variable([5, 5, 3, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64]) # 多通道卷积,卷积出64个特征 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7*7*64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 17]) b_fc2 = bias_variable([17]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv+1e-10), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # train_step = tf.train.GradientDescentOptimizer(1e-2).minimize(cross_entropy) # tf.summary.scalar("cross_entropy", cross_entropy) correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) merged_summary_op = tf.summary.merge_all() # 初始化变量 init_op = tf.global_variables_initializer() # summary_writer = tf.summary.FileWriter(log_path, graph=tf.get_default_graph()) # 开始训练 drops = [1.0, 0.8, 0.6, 0.4, 0.2] for i in range(len(drops)): drop = drops[i] log_path = logs_path + str(i) print("log_path: ", log_path, " drop:", drop) sess = tf.Session() sess.run(init_op) # iterate # Xtrain, ytrain = get_batch(self.args, self.simrank, self.walks, minibatch * 100, self.tem_simrank) # 找一个大点的数据集测试效果 # for i in range((int)(20000)): num_examples = trainX.shape[0] minibatch = 16 maxc = -1.0 for epoch in range(1000): # for epoch in range(1): print("iter:", epoch) avg_cost = 0.0 total_batch = int(num_examples / minibatch) # Loop over all batches for i in range(total_batch): batch_xs, batch_ys = next_batch(trainX, trainY, minibatch, num_examples) # print(type(batch_xs),type(batch_ys)) # print(batch_xs.shape, batch_ys.shape) # print(batch_xs[0]) # and summary nodes # print(sess.run(h_pool4, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # print(sess.run(y_conv, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # print(sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.8})) # return # print("batch_xs.shape: ", batch_xs.shape) # _, c, summary = sess.run([train_step, cross_entropy, merged_summary_op],feed_dict={x: batch_xs, y_: batch_ys, keep_prob: drop}) _, c = sess.run([train_step, cross_entropy], feed_dict={x: batch_xs, y_: batch_ys, keep_prob: drop}) # Write logs at every iteration # summary_writer.add_summary(summary, epoch * total_batch + i) # Compute average loss avg_cost += c / total_batch if (i % 1 == 0): print("i:", i, " current c:", c, " ave_cost:", avg_cost) # if i%1==0: # # print("valX.shape:", valX.shape, " valY.shape: ",valY.shape) # print("i: %d val accuracy %g" % (i, sess.run(accuracy, feed_dict={ # x: valX[0:10], y_: valY[0:10], keep_prob: 1.0}))) # print("i: %d test accuracy %g" % (i,sess.run(accuracy, feed_dict={ # x: testX, y_: testY, keep_prob: 1.0}))) # Display logs per epoch step # if (epoch + 1) % display_step == 0: print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost)) # 到达一定程度进行测试test输出 if epoch % 1 == 0: # batchs = mnist.train.next_batch(minibatch) acc = sess.run(accuracy, feed_dict={ x: testX, y_: testY, keep_prob: 1.0}) if acc > maxc: maxc = acc print("test accuracy %g" % acc) # x: batchs[0], y_: batchs[1], keep_prob: 1.0})) print("====================================================================") sess.close() print("maxc: ", maxc) print("finish!\n") print("finish all!") def next_batch(trainX, trainY, minibatch, num_examples): locations = random.sample([i for i in range(num_examples)], minibatch) batch_xs = trainX[locations] batch_ys = trainY[locations] return batch_xs, batch_ys if __name__ =="__main__": # 测试LeNet_5在minist数据集上效果 # CNN_LeNet_5_Mnist("./CNN/minist") # LeNet扩展,应用flower数据集 # drops = [0.8,1.0,0.6,0.4,0.2] # drops = [1.0, 0.8, 0.6, 0.4, 0.2] # drops = [0.8, 0.6, 0.4, 0.2] # for i in range(len(drops)): # print("drops: ", drops[i]) # CNN_LeNet_5_56("./flower_data/jpg/","./flower_data/datasplits.mat","./CNN/flower") CNN_LeNet_5_28("./flower_data/jpg/", "./flower_data/datasplits.mat", "./CNN/flower")
{ "repo_name": "songjs1993/DeepLearning", "path": "3CNN/CNN_LeNet_5.py", "copies": "1", "size": "20045", "license": "apache-2.0", "hash": 6044837463063899000, "line_mean": 39.1847133758, "line_max": 145, "alpha_frac": 0.569292545, "autogenerated": false, "ratio": 2.659780775716695, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8694296422652641, "avg_score": 0.00695537961281072, "num_lines": 471 }
# Auther: Alan """ 还没试,因为之前Disease.py没收敛 现在好像都收敛不了,尝试下VGG吧。 随机切割。。 """ import tensorflow as tf import random import os import scipy.io as sio # import matplotlib.pyplot as plt # plt import matplotlib.image as mpimg # mpimg import numpy as np # import Image import math from PIL import Image import xlrd class Disease: def __init__(self): print("init") def weight_variable(self,shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(self, shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(self, x, W): # strides return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME") def max_pool_2x2(self, x): return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME") def max_pool_3x3(self, x): return tf.nn.max_pool(x, ksize=[1,3,3,1], strides=[1,3,3,1], padding="SAME") def max_pool_5x5(self, x): return tf.nn.max_pool(x, ksize=[1,5,5,1], strides=[1,5,5,1], padding="SAME") def max_pool_10x10(self, x): return tf.nn.max_pool(x, ksize=[1,10,10,1], strides=[1,10,10,1], padding="SAME") def get_one_hot(self, label, num): y = [] for i in range(num): if i == label: y.append(1.0) else: y.append(0.0) return y def read_data_disease(self, input_file): """ 883 747 858 :return: """ allX,allY = [],[] locations, locations1, locations2 = [], [], [] with open(input_file + "trainX.txt", "r") as f1, open(input_file + "trainY.txt", "r") as f2: lines1 = f1.readlines() lines2 = f2.readlines() for i in range(len(lines1)): x = lines1[i][:-1] allX.append(x) label = lines2[i][:-1] if label=="G0": allY.append(0) elif label=="G0-1": allY.append(1) else: allY.append(2) if x[0:8] == "produce1" and x[-5]=="0": # add 1 locations1.append(i) elif x[0:8] == "produce2" and x[-5] == "0": # add 2 locations2.append(i) elif x[0]!='p': locations.append(i) # normal allX = np.array(allX) allY = np.array(allY) # normal print("length of locations: ", len(locations)) rate = 0.9 ls = random.sample(locations, int(len(locations)*rate)) trainX = list(allX[ls]) trainY = list(allY[ls]) ls = list(set(locations)-set(ls)) testX = list(allX[ls]) testY = list(allY[ls]) # add 1 def add_others(ls, trainX, trainY, allX, allY, num): for i in range(num): l = list(np.array(ls) + i) trainX.extend(allX[l]) trainY.extend(allY[l]) print("length of locations1: ", len(locations1)*3) ls = random.sample(locations1, int(len(locations1)*rate)) add_others(ls, trainX, trainY, allX, allY, 3) ls = list(set(locations1) - set(ls)) add_others(ls, testX, testY, allX, allY, 3) # add 2 print("length of locations2: ", len(locations2)*6) ls = random.sample(locations2, int(len(locations2)*rate)) add_others(ls, trainX, trainY, allX, allY, 6) ls = list(set(locations2) - set(ls)) add_others(ls, testX, testY, allX, allY, 6) trainX = np.array(trainX) trainY = np.array(trainY) testX = np.array(testX) testY = np.array(testY) print("shape of all data: ", trainX.shape, trainY.shape, testX.shape, testY.shape) cnt, cnt1, cnt2 = 0,0,0 for i in trainY: if i==0: cnt+=1 elif i==1: cnt1+=1 else: cnt2+=1 print("the number of the train data: ", cnt, cnt1, cnt2) return trainX, trainY, testX, testY def next_batch(self, trainX, trainY, minibatch, num_examples): locations = random.sample([i for i in range(num_examples)], minibatch) batch_xs_ = trainX[locations] batch_ys_ = trainY[locations] batch_xs, batch_ys = [], [] # print("minibatch:",minibatch) for i in range(batch_xs_.shape[0]): # print("i:", i) if i%50==0: print("deal with: ", i) batch = batch_xs_[i] # print("file:", batch) lena = Image.open("./data/G0/" + batch) first = random.sample([j for j in range(100)], 1)[0] second = random.sample([j for j in range(100)], 1)[0] lena = lena.crop((first, second, first + 600, second + 600)) # lena.save("temp.jpg") # lena = Image.open("temp.jpg") # print("new image.size:", lena.size) # print("batch_ys_[i]:", batch_ys_[i]) batch_xs.append(np.reshape(lena, [-1]) / 255.0) batch_ys.append(self.get_one_hot(batch_ys_[i], 3)) # one_hot return np.array(batch_xs), np.array(batch_ys) def get_test(self, testX, testY): # get test data in memory. batch_xs, batch_ys = [], [] for i in range(testX.shape[0]): if i%50==0: print("test i:", i) batch = testX[i] lena = Image.open("./data/G0/" + batch) first, second = 50, 50 lena = lena.crop((first, second, first + 600, second + 600)) batch_xs.append(np.reshape(lena, [-1]) / 255.0) batch_ys.append(self.get_one_hot(testY[i], 3)) # one_hot return np.array(batch_xs), np.array(batch_ys) def my_image_filter(self, x_image): self.h_conv1 = tf.nn.relu(self.conv2d(x_image, self.W_conv1) + self.b_conv1) self.h_pool1 = self.max_pool_2x2(self.h_conv1) # 300*300*32 self.h_conv2 = tf.nn.relu(self.conv2d(self.h_pool1, self.W_conv2) + self.b_conv2) self.h_pool2 = self.max_pool_5x5(self.h_conv2) # 60*60*32 self.h_conv3 = tf.nn.relu(self.conv2d(self.h_pool2, self.W_conv3) + self.b_conv3) self.h_conv4 = tf.nn.relu(self.conv2d(self.h_conv3, self.W_conv4_attr) + self.b_conv4_attr) self.h_pool4 = self.max_pool_2x2(self.h_conv4) # 30*30*64 self.h_conv5 = tf.nn.relu(self.conv2d(self.h_pool4, self.W_conv5_attr) + self.b_conv5_attr) self.h_pool5 = self.max_pool_5x5(self.h_conv5) # 6*6 self.h_flat1 = tf.reshape(self.h_pool5, [-1, 6 * 6 * 8]) self.h_flat1_drop = tf.nn.dropout(self.h_flat1, self.keep_prob) self.h_fc1 = tf.matmul(self.h_flat1_drop, self.W_fc1_attr) + self.b_fc1_attr self.h_fc_drop = tf.nn.dropout(self.h_fc1, self.keep_prob) self.y_conv = tf.matmul(self.h_fc_drop, self.W_fc2) + self.b_fc2 return self.y_conv def model(self, input_file, log_path): trainX, trainY, testX, testY = self.read_data_disease(input_file) cnt = 0 for i in testY: if i == 0: cnt += 1 print("minimal precision: ", float(cnt) / testY.shape[0]) # testX,testY = self.get_test(testX, testY, testX.shape[0], testY.shape[0]) self.keep_prob = tf.placeholder(tf.float32) self.x_ = tf.placeholder(tf.float32, [None, 600 * 600 * 3]) # shape [None, 128] self.x = tf.reshape(self.x_, [-1, 600, 600, 3]) self.W_conv1 = self.weight_variable([5, 5, 3, 8]) self.b_conv1 = self.bias_variable([8]) self.W_conv2 = self.weight_variable([3, 3, 8, 32]) self.b_conv2 = self.bias_variable([32]) self.W_conv3 = self.weight_variable([5, 5, 32, 32]) self.b_conv3 = self.bias_variable([32]) # attr self.W_conv4_attr = self.weight_variable([3, 3, 32, 16]) self.b_conv4_attr = self.bias_variable([16]) self.W_conv5_attr = self.weight_variable([3, 3, 16, 8]) self.b_conv5_attr = self.bias_variable([8]) self.W_fc1_attr = self.weight_variable([6 * 6 * 8, 36]) # 288 * 36 self.b_fc1_attr = self.bias_variable([36]) self.W_fc2 = self.weight_variable([36, 3]) self.b_fc2 = self.bias_variable([3]) self.y_ = tf.placeholder(tf.float32, [None, 3]) # shape [None, 3] self.y_conv = tf.nn.softmax(self.my_image_filter(self.x)) # self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.y_ * tf.log(self.y_conv + 1e-10), reduction_indices=[1])) self.cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.y_conv, labels=self.y_)) tf.summary.scalar("cross_entropy", self.cross_entropy) self.learning_rate = tf.placeholder(tf.float32, shape=[]) tf.summary.scalar("learning_rate", self.learning_rate) # self.train_step = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.cross_entropy) self.train_step = tf.train.AdamOptimizer(self.learning_rate).minimize(self.cross_entropy) self.correct_prediction = tf.equal(tf.arg_max(self.y_conv, 1), tf.arg_max(self.y_, 1)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) tf.summary.scalar("accuracy", self.accuracy) # init_op = tf.initialize_all_variables() init_op = tf.global_variables_initializer() self.merged_summary_op = tf.summary.merge_all() drops = [1.0] # overfitting. global_step = 201 for i in range(len(drops)): drop = drops[i] log_path = log_path + str(i) print("log_path: ", log_path, " drop:", drop) sess = tf.Session() sess.run(init_op) summary_writer_train = tf.summary.FileWriter(log_path + "train", graph=tf.get_default_graph()) summary_writer_test = tf.summary.FileWriter(log_path + "test", graph=tf.get_default_graph()) num_examples = trainX.shape[0] minibatch = 30 maxc = -1.0 for epoch in range(global_step): print("iter:", epoch) avg_cost = 0. total_batch = int(num_examples / minibatch) # total_batch = 1 rate = 0.001 * math.pow(0.7, int(epoch/15)) print("learning rate: ", rate) for i in range(total_batch): batch_xs, batch_ys = self.next_batch(trainX, trainY, minibatch, num_examples) # _, c, summary = sess.run([self.train_step, self.cross_entropy, self.merged_summary_op], feed_dict={self.x_: batch_xs, self.y_: batch_ys, self.learning_rate: rate, self.keep_prob: drop}) _, c , summary = sess.run([self.train_step, self.cross_entropy, self.merged_summary_op], feed_dict={self.x_: batch_xs, self.y_: batch_ys, self.learning_rate: rate, self.keep_prob: drop}) summary_writer_train.add_summary(summary, epoch * total_batch + i) avg_cost += c / total_batch if i%1==0: print("i/tot: ", i, "/", total_batch, " current c:", c, " ave_cost:", avg_cost) # test batch_xs, batch_ys = self.next_batch(testX, testY, minibatch, len(testY)) # batch_xs, batch_ys = self.next_batch_train(testX, testY, minibatch, len(testX)) pre, summary = sess.run([self.accuracy, self.merged_summary_op], feed_dict={self.x_: batch_xs, self.y_: batch_ys, self.learning_rate: rate, self.keep_prob: drop}) summary_writer_test.add_summary(summary, epoch * total_batch + i) if pre > maxc: maxc = pre # if epoch % 5 == 0 and epoch > 40: # pre, summary = sess.run([self.accuracy, self.merged_summary_op], feed_dict={self.x_: testX, self.y_: testY, self.keep_prob: drop}) # summary_writer.add_summary(summary, epoch * total_batch) # # print("precision: ", pre) # if pre > maxc: # maxc = pre print("max precision: ", maxc) if __name__ =="__main__": # CNN_LeNet_5_dev("./cifar_data/train.mat", "./cifar_data/test.mat", "./CNN/cifar") disease = Disease() disease.model("./data/", "./log_2_new_")
{ "repo_name": "songjs1993/DeepLearning", "path": "5Project/disease_classification/Disease.py", "copies": "1", "size": "12801", "license": "apache-2.0", "hash": 5586972919991105000, "line_mean": 37.8323170732, "line_max": 207, "alpha_frac": 0.5330140535, "autogenerated": false, "ratio": 3.147269582406721, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4180283635906721, "avg_score": null, "num_lines": null }
''' The MIT License (MIT) Copyright (c) 2014 Ahmet Besir Kurtulmus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' from random import randint import sys # Set the recırsion limit to 1,000,000 sys.setrecursionlimit(1000000) def Merge(list1, list2): """ Description: Merges two sorted lists. Args: list1 (List type): The first sorted list. list2 (List type): The second sorted list. Examples: >>> a = [1,3,5,7,9] >>> b = [2,4,6,8,10] >>> Merge(a,b) [1,2,3,4,5,6,7,8,9,10] """ if len(list1) == 0: return list2 if len(list2) == 0: return list1 if list1[0] <= list2[0]: return list1[:1] + Merge(list1[1:],list2) else: return list2[:1] + Merge(list1, list2[1:]) def MergeSortRecursive(l): """ Description: Sorts a list with the merge sort algorithm in a recursive fashion. Args: l (List type): The list which will be sorted. Examples: >>> l = [12, 32, 22, 21, 1, 75] >>> MergeSortRecursive(l) [1, 12, 21, 22, 32, 75] """ midPoint = len(l)/2 firstHalf = l[:midPoint] secondHalf = l[midPoint:] if len(l) > 1: return Merge(MergeSortRecursive(firstHalf), MergeSortRecursive(secondHalf)) else: return l def MergeSortIterative(l): """ Description: Sorts a list with the merge sort algorithm in a iterative fashion. Args: l (list type): The list which will be sorted Examples: >>> l = RandomList(10, 0, 1000) [631, 597, 27, 505, 54, 648, 809, 650, 384, 717] >>> MergeSortIterative(l) [27, 54, 384, 505, 597, 631, 648, 650, 717, 809] """ queue = [] for i in l: queue.append([i]) while len(queue) > 1: tmp = Merge(queue[0],queue[1]) queue = queue[2:] queue.append(tmp) return queue[0] def RandomList(length, min, max): """ Description: Generates a list with the given length. Args: length (int Type): The length of the randomly generated list. min (int type): The minimum possible number. max (int type): The maximum possible number. Examples: >>> RandomList(5) [3, 4, 8, 1, 6] """ l = [] for i in range(length): l.append(randint(min, max)) return l
{ "repo_name": "besirkurtulmus/AdvancedAlgorithms", "path": "Sorting/MergeSort.py", "copies": "1", "size": "3060", "license": "mit", "hash": 8919339279610623000, "line_mean": 25.8421052632, "line_max": 80, "alpha_frac": 0.7031709709, "autogenerated": false, "ratio": 3.0197433366238893, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4222914307523889, "avg_score": null, "num_lines": null }
__auther__='Jorgen Grimnes, Sudhanshu Patel' from sklearn import datasets import numpy as np from activation_functions import sigmoid_function, tanh_function, linear_function,\ LReLU_function, ReLU_function, symmetric_elliot_function, elliot_function from neuralnet import NeuralNet class Instance: # This is a simple encapsulation of a `input signal : output signal` # pair in out training set. def __init__(self, features, target): self.features = np.array(features) self.targets = np.array(target) #endclass Instance #------------------------------------------------------------------------------- ##Importing Iris data Set iris = datasets.load_iris() X = iris.data[:,] Y = iris.target inp=[] for i in range(0,len(X)): # preprocessing Iris data, in 4 input and 3 output format inp.append([list(X[i])]) if Y[i]==0: y=[1,0,0] elif Y[i]==1: y=[0,1,0] elif Y[i]==2: y=[0,0,1] inp[i].append(y) #training sets training_one =[] for i in range(len(inp)): training_one.append(Instance(inp[i][0],inp[i][1])) #Encapsulation of a `input signal : output signal #------------------------------------------------------------------------------ n_inputs = 4 # Number of input feature n_outputs = 3 # Number of neuron output n_hiddens = 8 # Number of neuron at each hidden layer n_hidden_layers = 2 # number of hidden layer # here 2 Hidden layer with 8 node each and 1 output layer with 3 node #------------------------DEclaration of activation or Transfer function at each layer --------------------------------------# # specify activation functions per layer eg: [ hidden_layer_1, hidden_layer_2, output_layer ] activation_functions = [symmetric_elliot_function,]*n_hidden_layers + [ sigmoid_function ] # initialize the neural network network = NeuralNet(n_inputs, n_outputs, n_hiddens, n_hidden_layers, activation_functions) # network is Instance of class Neuralnet # start training on test set one network.backpropagation(training_one, ERROR_LIMIT=.05, learning_rate=0.2, momentum_factor=0.2 ) # save the trained network network.save_to_file( "trained_configuration.pkl" ) # load a stored network configuration # network = NeuralNet.load_from_file( "trained_configuration.pkl" ) # print out the result for instance in training_one: print instance.features, network.forwordProp( np.array([instance.features]) ), "\ttarget:", instance.targets
{ "repo_name": "sudhanshuptl/python-neural-network", "path": "Iris_Data_Backprop/main.py", "copies": "1", "size": "2498", "license": "bsd-2-clause", "hash": -6622687449881503000, "line_mean": 35.7352941176, "line_max": 125, "alpha_frac": 0.6321056845, "autogenerated": false, "ratio": 3.711738484398217, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4843844168898217, "avg_score": null, "num_lines": null }
# @auther: Seven Lju # @date: 2015-08-06 from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from django.http import HttpResponse, Http404 from django.views.decorators.csrf import csrf_exempt def blankFile(f, size): print 'size =', size step = 10*1024*1024 # 10MB blank = '\0' * step while size > 0: if size < step: blank = '\0' * size f.write(blank) size -= step @csrf_exempt def savefile(request): if 'HTTP_UPLOAD_FILE_OFFSET' not in request.META: raise Http404() try: offset = int(request.META.get('HTTP_UPLOAD_FILE_OFFSET')) size = int(request.META.get('HTTP_UPLOAD_FILE_SIZE')) # it is better to have 2 kinds of apis: # - command api: open, close with uuid # - data api: like this function of savefiel to transport data if offset == 0: f = open('/tmp/upload.test', 'wb+') # reserve space in case of full disk blankFile(f, size) else: f = open('/tmp/upload.test', 'rb+') f.seek(offset) f.write(request.body) f.close() except: raise Http404() return HttpResponse('{}', content_type='application/json'); urlpatterns = patterns('', # Examples: # url(r'^$', 'upload.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^upload/$', 'upload.urls.savefile'), url(r'^admin/', include(admin.site.urls)), )
{ "repo_name": "dna2github/petalJS", "path": "upload/upload/urls.py", "copies": "3", "size": "1518", "license": "mit", "hash": 894887338188166100, "line_mean": 27.1111111111, "line_max": 70, "alpha_frac": 0.5895915679, "autogenerated": false, "ratio": 3.580188679245283, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.005510335009542029, "num_lines": 54 }
__auther__='Sudhanshu Patel' import xlrd #find top 3 frequently occuring genere Wbook = xlrd.open_workbook('PicturePerfect.xlsx') #global data def TopGenere(limit=3): #top n genere #print 'no of sheets ',Wbook.nsheets # we r goint to process only first sheet data = Wbook.sheet_by_index(0) genreState=dict() for row in range(1,data.nrows): gsplit=data.row_values(row)[1].split(',') for genre in gsplit: if genre in genreState: genreState[genre]+=1 else: genreState[genre] =1 #now find top limit no of genere ls=genreState.values() ls.sort(reverse=True) topgenre=[[ls[0]],[[ls[1]]],[ls[2]]] print len(topgenre) for genre in genreState: if genreState[genre]==ls[0]: topgenre[0].append(genre) elif genreState[genre]==ls[1]: topgenre[1].append(genre) elif genreState[genre]==ls[2]: topgenre[2].append(genre) #print "top 3 count genre' print topgenre[0] print topgenre[1] print topgenre[2] if __name__=='__main__': TopGenere()
{ "repo_name": "Hack22learn/Small-Application---Python", "path": "picturePerfect/top_genre.py", "copies": "2", "size": "1133", "license": "mit", "hash": 4249662938536166400, "line_mean": 26.6341463415, "line_max": 62, "alpha_frac": 0.5931156222, "autogenerated": false, "ratio": 3.303206997084548, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48963226192845477, "avg_score": null, "num_lines": null }
"""Auth handler""" from pyramid.httpexceptions import HTTPFound from pyramid.url import route_url from pyramid_handlers import action from webhelpers import paginate import uuid from haven.forms.account import LoginForm from haven.models.account import Account class AuthHandler(object): def __init__(self, request): self.request = request @action(renderer='auth/login.mako') def login(self): """Login view""" form = LoginForm(self.request.POST) session = self.request.session if self.request.method == 'POST' and form.validate(): account = Account.by_name(name=form.name.data) if account and account.check_password(form.password.data): # TODO: Storing ACL info in the session is insecure. authsession = {'id':uuid.UUID(bytes=account.id), 'name': account.name, 'is_admin' : account.is_admin} session["auth"] = authsession session.save() return HTTPFound(location = route_url('index', self.request)) return {'form':form, 'project':'BEAuth'} def logout(self): """logout view""" session = self.request.session session["auth"] = None session.delete() return HTTPFound(location = route_url('index', self.request))
{ "repo_name": "Niedra/Haven", "path": "haven/handlers/auth.py", "copies": "1", "size": "1354", "license": "isc", "hash": 7039729800064316000, "line_mean": 34.6315789474, "line_max": 86, "alpha_frac": 0.6211225997, "autogenerated": false, "ratio": 4.23125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004504825152244591, "num_lines": 38 }
# AuthHandler takes care of devising the auth type and using it class AuthHandler(): URL_SECRET = 2 URL_TOKEN = 3 def __init__(self, auth): self.auth = auth # Calculating the Authentication Type def get_auth_type(self): if 'client_id' in self.auth and 'client_secret' in self.auth: return self.URL_SECRET if 'access_token' in self.auth: return self.URL_TOKEN return -1 def set(self, request): if len(self.auth.keys()) == 0: return request auth = self.get_auth_type() flag = False if auth == self.URL_SECRET: request = self.url_secret(request) flag = True if auth == self.URL_TOKEN: request = self.url_token(request) flag = True if not flag: raise StandardError("Unable to calculate authorization method. Please check") return request # OAUTH2 Authorization with client secret def url_secret(self, request): request['params']['client_id'] = self.auth['client_id'] request['params']['client_secret'] = self.auth['client_secret'] return request # OAUTH2 Authorization with access token def url_token(self, request): request['params']['access_token'] = self.auth['access_token'] return request
{ "repo_name": "schevalier/Whetlab-Python-Client", "path": "whetlab/server/http_client/auth_handler.py", "copies": "1", "size": "1171", "license": "bsd-3-clause", "hash": 7120606539180506000, "line_mean": 21.9607843137, "line_max": 80, "alpha_frac": 0.6908625107, "autogenerated": false, "ratio": 3.2709497206703912, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9226857307785225, "avg_score": 0.04699098471703328, "num_lines": 51 }
import sys import os import csv import datetime from datetime import timedelta import re from re import sub from decimal import Decimal directory = '/Users/lkerxhalli/Documents/iris/jun12/' csvinputfile = directory + 'TransactionSearchResults374.csv' csvoutputfile = directory + 'VendorSummary374.csv' def main(): print ('--- Start ---') outdict = {} # key is composite of Vendor and Subsidiary header = ['Subsidiary', 'Vendor', 'Amount'] with open(csvinputfile, 'rU') as s_file: csv_r = csv.DictReader(s_file) index = 0 vendorName = '' maxAccount = 1 maxTempAccount = 0 maxServiceLine = 1 maxTempServiceLine = 0 maxLocation = 1 maxTempLocation = 0 maxDepartment = 1 maxTempDepartment = 0 for csv_row in csv_r: index += 1 # if index > 100: # break if csv_row['Name'] != '': vendorName = csv_row['Name'] if True: #vendorName == 'V19464 4900 Perry Highway Management LLC': subsidiary = csv_row['Subsidiary'] account = str(csv_row['Account'].split()[0]) amount = abs(float(csv_row['Amount'])) type = csv_row['Type'] serviceLine = csv_row['Service Line'] location = csv_row['Location'] department = csv_row['Department'] # print "%s| %s| %s| %s| %s" % (vendorName, csv_row['Account'], serviceLine, location, department) key = vendorName + subsidiary if not key in outdict: outdict[key] = {} if maxTempAccount > maxAccount: maxAccount = maxTempAccount maxTempAccount = 0 if maxTempServiceLine > maxServiceLine: maxServiceLine = maxTempServiceLine maxTempServiceLine = 0 if maxTempDepartment > maxDepartment: maxDepartment = maxTempDepartment maxTempDepartment = 0 if maxTempLocation > maxLocation: maxLocation = maxTempLocation maxTempLocation = 0 if account != '21000' and type == 'Bill': outdict[key]['Subsidiary'] = subsidiary outdict[key]['Vendor'] = vendorName if 'Amount' in outdict[key]: outdict[key]['Amount'] += amount else: outdict[key]['Amount'] = amount if not 'Accounts' in outdict[key]: outdict[key]['Accounts'] = set() outdict[key]['Accounts'].add(account) maxTempAccount = len(outdict[key]['Accounts']) if not 'ServiceLines' in outdict[key]: outdict[key]['ServiceLines'] = set() outdict[key]['ServiceLines'].add(serviceLine) maxTempServiceLine = len(outdict[key]['ServiceLines']) if not 'Departments' in outdict[key]: outdict[key]['Departments'] = set() outdict[key]['Departments'].add(department) maxTempDepartment = len(outdict[key]['Departments']) if not 'Locations' in outdict[key]: outdict[key]['Locations'] = set() outdict[key]['Locations'].add(location) maxTempLocation = len(outdict[key]['Locations']) print maxAccount for i in range(1, maxAccount + 1): header.append('Account {}'.format(i)) for i in range(1, maxServiceLine + 1): header.append('Service Line {}'.format(i)) for i in range(1, maxDepartment + 1): header.append('Department {}'.format(i)) for i in range(1, maxLocation + 1): header.append('Location {}'.format(i)) with open(csvoutputfile, 'w') as wfile: csvw = csv.writer(wfile, dialect='excel') csvw.writerow(header) for key in outdict: if 'Subsidiary' in outdict[key]: lastIndex = 0 row = [outdict[key]['Subsidiary'], outdict[key]['Vendor'], outdict[key]['Amount']] for acc in outdict[key]['Accounts']: row.append(acc) lastIndex += 1 tempIndex = lastIndex for i in range(tempIndex, maxAccount): row.append('') lastIndex += 1 for sline in outdict[key]['ServiceLines']: row.append(sline) lastIndex += 1 tempIndex = lastIndex for i in range(tempIndex, maxAccount+maxServiceLine): row.append('') lastIndex += 1 for dep in outdict[key]['Departments']: row.append(dep) lastIndex += 1 tempIndex = lastIndex for i in range(tempIndex, maxAccount+maxServiceLine+maxDepartment): row.append('') lastIndex += 1 for loc in outdict[key]['Locations']: row.append(loc) csvw.writerow(row) if __name__ == '__main__': main()
{ "repo_name": "lkerxhalli/tools", "path": "vendors/vendors.py", "copies": "1", "size": "5623", "license": "mit", "hash": 2135060376857435400, "line_mean": 36.9932432432, "line_max": 114, "alpha_frac": 0.5077360839, "autogenerated": false, "ratio": 4.424075531077891, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004414740588200974, "num_lines": 148 }
import sys import os import csv import datetime from datetime import timedelta import calendar from dateutil.relativedelta import * import re from re import sub from decimal import Decimal directory = '/Users/lkerxhalli/Documents/iris/jun14/' name = 'A_PPaymentHistorybyBill968' csvinputfile = directory + name + '.csv' csvoutputfile = directory + name + ' out.csv' hName = 'Name' hBill = 'Bills > 30' # change agingDays below if you change the number here as well hAvg = 'Avg.' hAvgAdjust = 'Avg. Adjusted' extraHeaders = 4 #headers that are not months agingDays = 30 #number of recent days to ignore from open bills # TODO continue # def isStringCompany(str): def parseName(str): p = re.compile(' V[0-9]{5}') m = p.search(str) if(m): index = m.end() + 1 return str[index:] else: return None def getDate(strDate): # check if strdate year part is 2 digit or 4 lIndex = strDate.rfind('/') + 1 # index of first digit strYear = strDate[lIndex:] if(len(strYear) == 2): return datetime.datetime.strptime(strDate, "%m/%d/%y").date() elif (len(strYear) == 4): return datetime.datetime.strptime(strDate, "%m/%d/%Y").date() else: return None def getMonthHeader(dt): year = dt.isocalendar()[0] month = dt.month strDt = "{} {}".format(calendar.month_abbr[month], year) return strDt def getNumber(strMoney): value = Decimal(sub(r'[^\d.]', '', strMoney)) if strMoney.find('(') > -1: value = value * -1 return value def isLineFull(strLine): arrLine = strLine.split(',') countFields = 0 for field in arrLine: if field: countFields += 1 if countFields > 4: return True else: return False def isOpenBillLine(strLine): arrLine = strLine.split(',') if len(arrLine) > 5 and arrLine[5]: return True else: return False def removeFileHeader(): with open(csvinputfile, 'r') as fin: data = fin.read().splitlines(True) noLinesToSkip = 0 for line in data: if isLineFull(line): # hdr = line.split(',') # strLine = '' # for item in hdr: # strLine += item.strip() + ',' # strLine = strLine[:-1] # data[noLinesToSkip] = strLine break else: noLinesToSkip += 1 with open(csvinputfile, 'w') as fout: fout.writelines(data[noLinesToSkip:]) def generateHeader(firstDate, lastDate): currentDate = firstDate header = [hName] while currentDate < lastDate: header.append(getMonthHeader(currentDate)) currentDate = currentDate + relativedelta(months=+1) #take care of last date lastMonthHeader = getMonthHeader(lastDate) if header[-1] != lastMonthHeader: header.append(lastMonthHeader) header.append(hBill) header.append(hAvg) header.append(hAvgAdjust) return header def main(): print ('-- Start --') print ('-- Clean csvs --') #let's remove any extra lines at the top (Titles etc) removeFileHeader() outdict = {} firstDate = getDate('01/01/40') #initialize them lastDate = getDate('01/01/10') months = 0 # number of months print ('-- reading AP --') #now read payment csv with open(csvinputfile, 'rU') as s_file: csv_r = csv.DictReader(s_file) tmpTransaction = '' # transaction string includes the vendor name for csv_row in csv_r: if csv_row['Transaction']: tmpTransaction = parseName(csv_row['Transaction']) if not tmpTransaction in outdict: outdict[tmpTransaction] = {} if csv_row['Payment Type'] == 'Bill': dt = getDate(csv_row['Date']) month = getMonthHeader(dt) if dt > lastDate: lastDate = dt if dt < firstDate: firstDate = dt amount = getNumber(csv_row['Amount']) if not month in outdict[tmpTransaction]: outdict[tmpTransaction][month] = amount else: outdict[tmpTransaction][month] += amount header = generateHeader(firstDate, lastDate) months = len(header) - extraHeaders print ('Number of months: {}'.format(months)) #calculate and add averages for vendor in outdict: avg = 0 for key in outdict[vendor]: if key != hName and key != hBill: avg += outdict[vendor][key] if months > 0: outdict[vendor][hAvg] = round(avg/months, 2) if hBill in outdict[vendor]: outdict[vendor][hAvgAdjust] = round((avg + outdict[vendor][hBill])/months, 2) else: outdict[vendor][hAvgAdjust] = outdict[vendor][hAvg] print ('-- Completing Calculations --') #TODO: find and Sort for TNE for the names # for python 3 use below to prevent extra blank lines # with open(csvoutputfile, 'w', newline='') as wfile: with open(csvoutputfile, 'w') as wfile: csvw = csv.writer(wfile, dialect='excel') csvw.writerow(header) for key in outdict: if key: row = [key] for col in header[1:]: if col in outdict[key]: row.append(outdict[key][col]) else: row.append(0) csvw.writerow(row) print ('-- finito --') if __name__ == '__main__': main()
{ "repo_name": "lkerxhalli/tools", "path": "payments/invoices.py", "copies": "1", "size": "5836", "license": "mit", "hash": 1322124914766140200, "line_mean": 26.2710280374, "line_max": 93, "alpha_frac": 0.5781357094, "autogenerated": false, "ratio": 3.792072774528915, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4870208483928915, "avg_score": null, "num_lines": null }
import sys import os import csv import datetime from datetime import timedelta import re from re import sub from decimal import Decimal directory = '/Users/lkerxhalli/Documents/iris/jan29/' fname = 'CIS' csvinputfile = directory + fname + ' payments.csv' csvopenbills = directory + fname + ' open bills.csv' csvoutputfile = directory + fname + ' out.csv' hName = 'Name' hBill = 'Bills > 30' # change agingDays below if you change the number here as well hAvg = 'Avg.' hAvgAdjust = 'Avg. Adjusted' extraHeaders = 4 #headers that are not weeks agingDays = 30 #number of recent days to ignore from open bills # TODO continue # def isStringCompany(str): def parseName(str): p = re.compile('V[0-9]{5}') m = p.search(str) if(m): index = m.end() + 1 return str[index:] else: return None def getDate(strDate): # check if strdate year part is 2 digit or 4 lIndex = strDate.rfind('/') + 1 # index of first digit strYear = strDate[lIndex:] if(len(strYear) == 2): return datetime.datetime.strptime(strDate, "%m/%d/%y").date() elif (len(strYear) == 4): return datetime.datetime.strptime(strDate, "%m/%d/%Y").date() else: return None def getWeekHeader(dt): year = dt.isocalendar()[0] weekNo = dt.isocalendar()[1] strDt = "{}-W{}".format(year, weekNo) monday = datetime.datetime.strptime(strDt + '-1', "%Y-W%W-%w") sunday = monday + datetime.timedelta(days=6) return monday.strftime('%m/%d/%y') + ' - ' + sunday.strftime('%m/%d/%y') def getNumber(strMoney): value = Decimal(sub(r'[^\d.]', '', strMoney)) return value def isLineFull(strLine): arrLine = strLine.split(',') countFields = 0 for field in arrLine: if field: countFields += 1 if countFields > 4: return True else: return False def isOpenBillLine(strLine): arrLine = strLine.split(',') if len(arrLine) > 5 and arrLine[5]: return True else: return False def removeFileHeader(): with open(csvinputfile, 'r') as fin: data = fin.read().splitlines(True) noLinesToSkip = 0 for line in data: if isLineFull(line): break else: noLinesToSkip += 1 with open(csvinputfile, 'w') as fout: fout.writelines(data[noLinesToSkip:]) # clean open bills with open(csvopenbills, 'rU') as fin: data = fin.read().splitlines(True) outData = [] for line in data: if isOpenBillLine(line): outData.append(line) with open(csvopenbills, 'w') as fout: fout.writelines(outData) def generateHeader(firstDate, lastDate): currentDate = firstDate header = [hName] while currentDate < lastDate: header.append(getWeekHeader(currentDate)) currentDate = currentDate + timedelta(days=7) #take care of last date lastWeekHeader = getWeekHeader(lastDate) if header[-1] != lastWeekHeader: header.append(lastWeekHeader) header.append(hBill) header.append(hAvg) header.append(hAvgAdjust) return header def main(): print ('-- Start --') print ('-- Clean csvs --') #let's remove any extra lines at the top (Titles etc) removeFileHeader() outdict = {} firstDate = getDate('01/01/40') #initialize them lastDate = getDate('01/01/10') weeks = 0 # number of weeks print ('-- reading AP --') #now read payment csv with open(csvinputfile, 'rU') as s_file: csv_r = csv.DictReader(s_file) tmpTransaction = '' # transaction string includes the vendor name for csv_row in csv_r: if csv_row['Transaction']: tmpTransaction = parseName(csv_row['Transaction']) if not tmpTransaction in outdict: outdict[tmpTransaction] = {} if csv_row['Bill Type'] == 'Bill Payment' or csv_row['Bill Type'] == 'JE': dt = getDate(csv_row['Date']) week = getWeekHeader(dt) if dt > lastDate: lastDate = dt if dt < firstDate: firstDate = dt amount = getNumber(csv_row['Amount']) if not week in outdict[tmpTransaction]: outdict[tmpTransaction][week] = amount else: outdict[tmpTransaction][week] += amount header = generateHeader(firstDate, lastDate) weeks = len(header) - extraHeaders print ('Number of weeks: {}'.format(weeks)) #read open bills csv print ('-- reading open bills --') openBillsDict = {} with open(csvopenbills, 'rU') as s_file: csv_r = csv.DictReader(s_file) for csv_row in csv_r: if getDate(csv_row['Date Due']): delta = datetime.date.today() - getDate(csv_row['Date Due']) if(delta.days > 30): vendor = parseName(csv_row['Vendor']) amount = getNumber(csv_row['Amount Due']) if vendor in openBillsDict: openBillsDict[vendor] += amount else: openBillsDict[vendor] = amount #add open bills to the main dictionary for vendor in openBillsDict: if vendor in outdict: outdict[vendor][hBill] = openBillsDict[vendor] #calculate and add averages for vendor in outdict: avg = 0 for key in outdict[vendor]: if key != hName and key != hBill: avg += outdict[vendor][key] if weeks > 0: outdict[vendor][hAvg] = round(avg/weeks, 2) if hBill in outdict[vendor]: outdict[vendor][hAvgAdjust] = round((avg + outdict[vendor][hBill])/weeks, 2) else: outdict[vendor][hAvgAdjust] = outdict[vendor][hAvg] print ('-- Completing Calculations --') #TODO: find and Sort for TNE for the names # for python 3 use below to prevent extra blank lines # with open(csvoutputfile, 'w', newline='') as wfile: with open(csvoutputfile, 'w') as wfile: csvw = csv.writer(wfile, dialect='excel') csvw.writerow(header) for key in outdict: if key: row = [key] for col in header[1:]: if col in outdict[key]: row.append(outdict[key][col]) else: row.append(0) csvw.writerow(row) print ('-- finito --') if __name__ == '__main__': main()
{ "repo_name": "lkerxhalli/tools", "path": "payments/payments.py", "copies": "1", "size": "5915", "license": "mit", "hash": 4930711768281848000, "line_mean": 24.063559322, "line_max": 83, "alpha_frac": 0.6713440406, "autogenerated": false, "ratio": 2.9589794897448725, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4130323530344872, "avg_score": null, "num_lines": null }
import sys import os import csv import datetime from datetime import timedelta import re from re import sub from decimal import Decimal directory = '/Users/lkerxhalli/Documents/iris/jun13/' name = 'NPS 1.1.19 4.30.19' csvinputfile = directory + name + '.csv' csvoutputfile = directory + name + ' out.csv' hName = 'Name' hBill = 'Bills > 30' # change agingDays below if you change the number here as well hAvg = 'Avg.' hAvgAdjust = 'Avg. Adjusted' extraHeaders = 4 #headers that are not weeks agingDays = 30 #number of recent days to ignore from open bills # TODO continue # def isStringCompany(str): def parseName(str): p = re.compile('V[0-9]{5}') m = p.search(str) if(m): index = m.end() + 1 return str[index:] else: return None def getDate(strDate): # check if strdate year part is 2 digit or 4 lIndex = strDate.rfind('/') + 1 # index of first digit strYear = strDate[lIndex:] if(len(strYear) == 2): return datetime.datetime.strptime(strDate, "%m/%d/%y").date() elif (len(strYear) == 4): return datetime.datetime.strptime(strDate, "%m/%d/%Y").date() else: return None def getWeekHeader(dt): year = dt.isocalendar()[0] weekNo = dt.isocalendar()[1] strDt = "{}-W{}".format(year, weekNo) monday = datetime.datetime.strptime(strDt + '-1', "%Y-W%W-%w") sunday = monday + datetime.timedelta(days=6) return monday.strftime('%m/%d/%y') + ' - ' + sunday.strftime('%m/%d/%y') def getNumber(strMoney): value = Decimal(sub(r'[^\d.]', '', strMoney)) if strMoney.find('(') > -1: value = value * -1 return value def isLineFull(strLine): arrLine = strLine.split(',') countFields = 0 for field in arrLine: if field: countFields += 1 if countFields > 4: return True else: return False def isOpenBillLine(strLine): arrLine = strLine.split(',') if len(arrLine) > 5 and arrLine[5]: return True else: return False def removeFileHeader(): with open(csvinputfile, 'r') as fin: data = fin.read().splitlines(True) noLinesToSkip = 0 for line in data: if isLineFull(line): # hdr = line.split(',') # strLine = '' # for item in hdr: # strLine += item.strip() + ',' # strLine = strLine[:-1] # data[noLinesToSkip] = strLine break else: noLinesToSkip += 1 with open(csvinputfile, 'w') as fout: fout.writelines(data[noLinesToSkip:]) def generateHeader(firstDate, lastDate): currentDate = firstDate header = [hName] while currentDate < lastDate: header.append(getWeekHeader(currentDate)) currentDate = currentDate + timedelta(days=7) #take care of last date lastWeekHeader = getWeekHeader(lastDate) if header[-1] != lastWeekHeader: header.append(lastWeekHeader) header.append(hBill) header.append(hAvg) header.append(hAvgAdjust) return header def main(): print ('-- Start --') print ('-- Clean csvs --') #let's remove any extra lines at the top (Titles etc) removeFileHeader() outdict = {} firstDate = getDate('01/01/40') #initialize them lastDate = getDate('01/01/10') weeks = 0 # number of weeks print ('-- reading AP --') #now read payment csv with open(csvinputfile, 'rU') as s_file: csv_r = csv.DictReader(s_file) tmpTransaction = '' # transaction string includes the vendor name for csv_row in csv_r: if csv_row['Transaction']: tmpTransaction = parseName(csv_row['Transaction']) if not tmpTransaction in outdict: outdict[tmpTransaction] = {} if csv_row['Bill Type'] == 'Bill Payment' or csv_row['Bill Type'] == 'JE': dt = getDate(csv_row['Date']) week = getWeekHeader(dt) if dt > lastDate: lastDate = dt if dt < firstDate: firstDate = dt amount = getNumber(csv_row['Amount']) if not week in outdict[tmpTransaction]: outdict[tmpTransaction][week] = amount else: outdict[tmpTransaction][week] += amount header = generateHeader(firstDate, lastDate) weeks = len(header) - extraHeaders print ('Number of weeks: {}'.format(weeks)) #calculate and add averages for vendor in outdict: avg = 0 for key in outdict[vendor]: if key != hName and key != hBill: avg += outdict[vendor][key] if weeks > 0: outdict[vendor][hAvg] = round(avg/weeks, 2) if hBill in outdict[vendor]: outdict[vendor][hAvgAdjust] = round((avg + outdict[vendor][hBill])/weeks, 2) else: outdict[vendor][hAvgAdjust] = outdict[vendor][hAvg] print ('-- Completing Calculations --') #TODO: find and Sort for TNE for the names # for python 3 use below to prevent extra blank lines # with open(csvoutputfile, 'w', newline='') as wfile: with open(csvoutputfile, 'w') as wfile: csvw = csv.writer(wfile, dialect='excel') csvw.writerow(header) for key in outdict: if key: row = [key] for col in header[1:]: if col in outdict[key]: row.append(outdict[key][col]) else: row.append(0) csvw.writerow(row) print ('-- finito --') if __name__ == '__main__': main()
{ "repo_name": "lkerxhalli/tools", "path": "payments/paymentswobill.py", "copies": "1", "size": "5997", "license": "mit", "hash": 6765552083399382000, "line_mean": 27.1549295775, "line_max": 92, "alpha_frac": 0.5729531432, "autogenerated": false, "ratio": 3.688191881918819, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4761145025118819, "avg_score": null, "num_lines": null }
"""Auth models.""" from datetime import datetime, timedelta from typing import Dict, List, NamedTuple, Optional import uuid import attr from homeassistant.util import dt as dt_util from . import permissions as perm_mdl from .const import GROUP_ID_ADMIN from .util import generate_secret TOKEN_TYPE_NORMAL = "normal" TOKEN_TYPE_SYSTEM = "system" TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token" @attr.s(slots=True) class Group: """A group.""" name = attr.ib(type=Optional[str]) policy = attr.ib(type=perm_mdl.PolicyType) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) system_generated = attr.ib(type=bool, default=False) @attr.s(slots=True) class User: """A user.""" name = attr.ib(type=Optional[str]) perm_lookup = attr.ib(type=perm_mdl.PermissionLookup, cmp=False) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_owner = attr.ib(type=bool, default=False) is_active = attr.ib(type=bool, default=False) system_generated = attr.ib(type=bool, default=False) groups = attr.ib(type=List[Group], factory=list, cmp=False) # List of credentials of a user. credentials = attr.ib(type=List["Credentials"], factory=list, cmp=False) # Tokens associated with a user. refresh_tokens = attr.ib(type=Dict[str, "RefreshToken"], factory=dict, cmp=False) _permissions = attr.ib( type=Optional[perm_mdl.PolicyPermissions], init=False, cmp=False, default=None ) @property def permissions(self) -> perm_mdl.AbstractPermissions: """Return permissions object for user.""" if self.is_owner: return perm_mdl.OwnerPermissions if self._permissions is not None: return self._permissions self._permissions = perm_mdl.PolicyPermissions( perm_mdl.merge_policies([group.policy for group in self.groups]), self.perm_lookup, ) return self._permissions @property def is_admin(self) -> bool: """Return if user is part of the admin group.""" if self.is_owner: return True return self.is_active and any(gr.id == GROUP_ID_ADMIN for gr in self.groups) def invalidate_permission_cache(self) -> None: """Invalidate permission cache.""" self._permissions = None @attr.s(slots=True) class RefreshToken: """RefreshToken for a user to grant new access tokens.""" user = attr.ib(type=User) client_id = attr.ib(type=Optional[str]) access_token_expiration = attr.ib(type=timedelta) client_name = attr.ib(type=Optional[str], default=None) client_icon = attr.ib(type=Optional[str], default=None) token_type = attr.ib( type=str, default=TOKEN_TYPE_NORMAL, validator=attr.validators.in_( (TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN) ), ) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) created_at = attr.ib(type=datetime, factory=dt_util.utcnow) token = attr.ib(type=str, factory=lambda: generate_secret(64)) jwt_key = attr.ib(type=str, factory=lambda: generate_secret(64)) last_used_at = attr.ib(type=Optional[datetime], default=None) last_used_ip = attr.ib(type=Optional[str], default=None) @attr.s(slots=True) class Credentials: """Credentials for a user on an auth provider.""" auth_provider_type = attr.ib(type=str) auth_provider_id = attr.ib(type=Optional[str]) # Allow the auth provider to store data to represent their auth. data = attr.ib(type=dict) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_new = attr.ib(type=bool, default=True) UserMeta = NamedTuple("UserMeta", [("name", Optional[str]), ("is_active", bool)])
{ "repo_name": "joopert/home-assistant", "path": "homeassistant/auth/models.py", "copies": "3", "size": "3773", "license": "apache-2.0", "hash": 6942480508589013000, "line_mean": 30.4416666667, "line_max": 86, "alpha_frac": 0.6649880732, "autogenerated": false, "ratio": 3.439380127620784, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00048813533797869234, "num_lines": 120 }
"""Auth models.""" from datetime import datetime, timedelta from typing import Dict, List, NamedTuple, Optional # noqa: F401 import uuid import attr from homeassistant.util import dt as dt_util from . import permissions as perm_mdl from .const import GROUP_ID_ADMIN from .util import generate_secret TOKEN_TYPE_NORMAL = 'normal' TOKEN_TYPE_SYSTEM = 'system' TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = 'long_lived_access_token' @attr.s(slots=True) class Group: """A group.""" name = attr.ib(type=str) # type: Optional[str] policy = attr.ib(type=perm_mdl.PolicyType) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) system_generated = attr.ib(type=bool, default=False) @attr.s(slots=True) class User: """A user.""" name = attr.ib(type=str) # type: Optional[str] perm_lookup = attr.ib( type=perm_mdl.PermissionLookup, cmp=False, ) # type: perm_mdl.PermissionLookup id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_owner = attr.ib(type=bool, default=False) is_active = attr.ib(type=bool, default=False) system_generated = attr.ib(type=bool, default=False) groups = attr.ib(type=List, factory=list, cmp=False) # type: List[Group] # List of credentials of a user. credentials = attr.ib( type=list, factory=list, cmp=False ) # type: List[Credentials] # Tokens associated with a user. refresh_tokens = attr.ib( type=dict, factory=dict, cmp=False ) # type: Dict[str, RefreshToken] _permissions = attr.ib( type=Optional[perm_mdl.PolicyPermissions], init=False, cmp=False, default=None, ) @property def permissions(self) -> perm_mdl.AbstractPermissions: """Return permissions object for user.""" if self.is_owner: return perm_mdl.OwnerPermissions if self._permissions is not None: return self._permissions self._permissions = perm_mdl.PolicyPermissions( perm_mdl.merge_policies([ group.policy for group in self.groups]), self.perm_lookup) return self._permissions @property def is_admin(self) -> bool: """Return if user is part of the admin group.""" if self.is_owner: return True return self.is_active and any( gr.id == GROUP_ID_ADMIN for gr in self.groups) def invalidate_permission_cache(self) -> None: """Invalidate permission cache.""" self._permissions = None @attr.s(slots=True) class RefreshToken: """RefreshToken for a user to grant new access tokens.""" user = attr.ib(type=User) client_id = attr.ib(type=Optional[str]) access_token_expiration = attr.ib(type=timedelta) client_name = attr.ib(type=Optional[str], default=None) client_icon = attr.ib(type=Optional[str], default=None) token_type = attr.ib(type=str, default=TOKEN_TYPE_NORMAL, validator=attr.validators.in_(( TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN))) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) created_at = attr.ib(type=datetime, factory=dt_util.utcnow) token = attr.ib(type=str, factory=lambda: generate_secret(64)) jwt_key = attr.ib(type=str, factory=lambda: generate_secret(64)) last_used_at = attr.ib(type=Optional[datetime], default=None) last_used_ip = attr.ib(type=Optional[str], default=None) @attr.s(slots=True) class Credentials: """Credentials for a user on an auth provider.""" auth_provider_type = attr.ib(type=str) auth_provider_id = attr.ib(type=Optional[str]) # Allow the auth provider to store data to represent their auth. data = attr.ib(type=dict) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_new = attr.ib(type=bool, default=True) UserMeta = NamedTuple("UserMeta", [('name', Optional[str]), ('is_active', bool)])
{ "repo_name": "HydrelioxGitHub/home-assistant", "path": "homeassistant/auth/models.py", "copies": "12", "size": "4027", "license": "apache-2.0", "hash": 1218640237234901800, "line_mean": 30.4609375, "line_max": 77, "alpha_frac": 0.6411720884, "autogenerated": false, "ratio": 3.5017391304347827, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 128 }
"""Auth models.""" from datetime import datetime, timedelta import secrets from typing import Dict, List, NamedTuple, Optional import uuid import attr from homeassistant.const import __version__ from homeassistant.util import dt as dt_util from . import permissions as perm_mdl from .const import GROUP_ID_ADMIN TOKEN_TYPE_NORMAL = "normal" TOKEN_TYPE_SYSTEM = "system" TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token" @attr.s(slots=True) class Group: """A group.""" name: Optional[str] = attr.ib() policy: perm_mdl.PolicyType = attr.ib() id: str = attr.ib(factory=lambda: uuid.uuid4().hex) system_generated: bool = attr.ib(default=False) @attr.s(slots=True) class User: """A user.""" name: Optional[str] = attr.ib() perm_lookup: perm_mdl.PermissionLookup = attr.ib(eq=False, order=False) id: str = attr.ib(factory=lambda: uuid.uuid4().hex) is_owner: bool = attr.ib(default=False) is_active: bool = attr.ib(default=False) system_generated: bool = attr.ib(default=False) groups: List[Group] = attr.ib(factory=list, eq=False, order=False) # List of credentials of a user. credentials: List["Credentials"] = attr.ib(factory=list, eq=False, order=False) # Tokens associated with a user. refresh_tokens: Dict[str, "RefreshToken"] = attr.ib( factory=dict, eq=False, order=False ) _permissions: Optional[perm_mdl.PolicyPermissions] = attr.ib( init=False, eq=False, order=False, default=None, ) @property def permissions(self) -> perm_mdl.AbstractPermissions: """Return permissions object for user.""" if self.is_owner: return perm_mdl.OwnerPermissions if self._permissions is not None: return self._permissions self._permissions = perm_mdl.PolicyPermissions( perm_mdl.merge_policies([group.policy for group in self.groups]), self.perm_lookup, ) return self._permissions @property def is_admin(self) -> bool: """Return if user is part of the admin group.""" if self.is_owner: return True return self.is_active and any(gr.id == GROUP_ID_ADMIN for gr in self.groups) def invalidate_permission_cache(self) -> None: """Invalidate permission cache.""" self._permissions = None @attr.s(slots=True) class RefreshToken: """RefreshToken for a user to grant new access tokens.""" user: User = attr.ib() client_id: Optional[str] = attr.ib() access_token_expiration: timedelta = attr.ib() client_name: Optional[str] = attr.ib(default=None) client_icon: Optional[str] = attr.ib(default=None) token_type: str = attr.ib( default=TOKEN_TYPE_NORMAL, validator=attr.validators.in_( (TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN) ), ) id: str = attr.ib(factory=lambda: uuid.uuid4().hex) created_at: datetime = attr.ib(factory=dt_util.utcnow) token: str = attr.ib(factory=lambda: secrets.token_hex(64)) jwt_key: str = attr.ib(factory=lambda: secrets.token_hex(64)) last_used_at: Optional[datetime] = attr.ib(default=None) last_used_ip: Optional[str] = attr.ib(default=None) credential: Optional["Credentials"] = attr.ib(default=None) version: Optional[str] = attr.ib(default=__version__) @attr.s(slots=True) class Credentials: """Credentials for a user on an auth provider.""" auth_provider_type: str = attr.ib() auth_provider_id: Optional[str] = attr.ib() # Allow the auth provider to store data to represent their auth. data: dict = attr.ib() id: str = attr.ib(factory=lambda: uuid.uuid4().hex) is_new: bool = attr.ib(default=True) class UserMeta(NamedTuple): """User metadata.""" name: Optional[str] is_active: bool
{ "repo_name": "partofthething/home-assistant", "path": "homeassistant/auth/models.py", "copies": "2", "size": "3896", "license": "mit", "hash": -427211423434978800, "line_mean": 28.2932330827, "line_max": 86, "alpha_frac": 0.6532340862, "autogenerated": false, "ratio": 3.497307001795332, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5150541087995332, "avg_score": null, "num_lines": null }
"""Auth models.""" from datetime import datetime, timedelta import secrets from typing import Dict, List, NamedTuple, Optional import uuid import attr from homeassistant.util import dt as dt_util from . import permissions as perm_mdl from .const import GROUP_ID_ADMIN TOKEN_TYPE_NORMAL = "normal" TOKEN_TYPE_SYSTEM = "system" TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token" @attr.s(slots=True) class Group: """A group.""" name = attr.ib(type=Optional[str]) policy = attr.ib(type=perm_mdl.PolicyType) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) system_generated = attr.ib(type=bool, default=False) @attr.s(slots=True) class User: """A user.""" name = attr.ib(type=Optional[str]) perm_lookup = attr.ib(type=perm_mdl.PermissionLookup, cmp=False) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_owner = attr.ib(type=bool, default=False) is_active = attr.ib(type=bool, default=False) system_generated = attr.ib(type=bool, default=False) groups = attr.ib(type=List[Group], factory=list, cmp=False) # List of credentials of a user. credentials = attr.ib(type=List["Credentials"], factory=list, cmp=False) # Tokens associated with a user. refresh_tokens = attr.ib(type=Dict[str, "RefreshToken"], factory=dict, cmp=False) _permissions = attr.ib( type=Optional[perm_mdl.PolicyPermissions], init=False, cmp=False, default=None ) @property def permissions(self) -> perm_mdl.AbstractPermissions: """Return permissions object for user.""" if self.is_owner: return perm_mdl.OwnerPermissions if self._permissions is not None: return self._permissions self._permissions = perm_mdl.PolicyPermissions( perm_mdl.merge_policies([group.policy for group in self.groups]), self.perm_lookup, ) return self._permissions @property def is_admin(self) -> bool: """Return if user is part of the admin group.""" if self.is_owner: return True return self.is_active and any(gr.id == GROUP_ID_ADMIN for gr in self.groups) def invalidate_permission_cache(self) -> None: """Invalidate permission cache.""" self._permissions = None @attr.s(slots=True) class RefreshToken: """RefreshToken for a user to grant new access tokens.""" user = attr.ib(type=User) client_id = attr.ib(type=Optional[str]) access_token_expiration = attr.ib(type=timedelta) client_name = attr.ib(type=Optional[str], default=None) client_icon = attr.ib(type=Optional[str], default=None) token_type = attr.ib( type=str, default=TOKEN_TYPE_NORMAL, validator=attr.validators.in_( (TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN) ), ) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) created_at = attr.ib(type=datetime, factory=dt_util.utcnow) token = attr.ib(type=str, factory=lambda: secrets.token_hex(64)) jwt_key = attr.ib(type=str, factory=lambda: secrets.token_hex(64)) last_used_at = attr.ib(type=Optional[datetime], default=None) last_used_ip = attr.ib(type=Optional[str], default=None) @attr.s(slots=True) class Credentials: """Credentials for a user on an auth provider.""" auth_provider_type = attr.ib(type=str) auth_provider_id = attr.ib(type=Optional[str]) # Allow the auth provider to store data to represent their auth. data = attr.ib(type=dict) id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) is_new = attr.ib(type=bool, default=True) UserMeta = NamedTuple("UserMeta", [("name", Optional[str]), ("is_active", bool)])
{ "repo_name": "leppa/home-assistant", "path": "homeassistant/auth/models.py", "copies": "2", "size": "3758", "license": "apache-2.0", "hash": -8796732767231070000, "line_mean": 30.3166666667, "line_max": 86, "alpha_frac": 0.6641830761, "autogenerated": false, "ratio": 3.428832116788321, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5093015192888322, "avg_score": null, "num_lines": null }
"""Auth models.""" from __future__ import annotations from datetime import datetime, timedelta import secrets from typing import NamedTuple import uuid import attr from homeassistant.const import __version__ from homeassistant.util import dt as dt_util from . import permissions as perm_mdl from .const import GROUP_ID_ADMIN TOKEN_TYPE_NORMAL = "normal" TOKEN_TYPE_SYSTEM = "system" TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token" @attr.s(slots=True) class Group: """A group.""" name: str | None = attr.ib() policy: perm_mdl.PolicyType = attr.ib() id: str = attr.ib(factory=lambda: uuid.uuid4().hex) system_generated: bool = attr.ib(default=False) @attr.s(slots=True) class User: """A user.""" name: str | None = attr.ib() perm_lookup: perm_mdl.PermissionLookup = attr.ib(eq=False, order=False) id: str = attr.ib(factory=lambda: uuid.uuid4().hex) is_owner: bool = attr.ib(default=False) is_active: bool = attr.ib(default=False) system_generated: bool = attr.ib(default=False) groups: list[Group] = attr.ib(factory=list, eq=False, order=False) # List of credentials of a user. credentials: list[Credentials] = attr.ib(factory=list, eq=False, order=False) # Tokens associated with a user. refresh_tokens: dict[str, RefreshToken] = attr.ib( factory=dict, eq=False, order=False ) _permissions: perm_mdl.PolicyPermissions | None = attr.ib( init=False, eq=False, order=False, default=None, ) @property def permissions(self) -> perm_mdl.AbstractPermissions: """Return permissions object for user.""" if self.is_owner: return perm_mdl.OwnerPermissions if self._permissions is not None: return self._permissions self._permissions = perm_mdl.PolicyPermissions( perm_mdl.merge_policies([group.policy for group in self.groups]), self.perm_lookup, ) return self._permissions @property def is_admin(self) -> bool: """Return if user is part of the admin group.""" if self.is_owner: return True return self.is_active and any(gr.id == GROUP_ID_ADMIN for gr in self.groups) def invalidate_permission_cache(self) -> None: """Invalidate permission cache.""" self._permissions = None @attr.s(slots=True) class RefreshToken: """RefreshToken for a user to grant new access tokens.""" user: User = attr.ib() client_id: str | None = attr.ib() access_token_expiration: timedelta = attr.ib() client_name: str | None = attr.ib(default=None) client_icon: str | None = attr.ib(default=None) token_type: str = attr.ib( default=TOKEN_TYPE_NORMAL, validator=attr.validators.in_( (TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN) ), ) id: str = attr.ib(factory=lambda: uuid.uuid4().hex) created_at: datetime = attr.ib(factory=dt_util.utcnow) token: str = attr.ib(factory=lambda: secrets.token_hex(64)) jwt_key: str = attr.ib(factory=lambda: secrets.token_hex(64)) last_used_at: datetime | None = attr.ib(default=None) last_used_ip: str | None = attr.ib(default=None) credential: Credentials | None = attr.ib(default=None) version: str | None = attr.ib(default=__version__) @attr.s(slots=True) class Credentials: """Credentials for a user on an auth provider.""" auth_provider_type: str = attr.ib() auth_provider_id: str | None = attr.ib() # Allow the auth provider to store data to represent their auth. data: dict = attr.ib() id: str = attr.ib(factory=lambda: uuid.uuid4().hex) is_new: bool = attr.ib(default=True) class UserMeta(NamedTuple): """User metadata.""" name: str | None is_active: bool
{ "repo_name": "sander76/home-assistant", "path": "homeassistant/auth/models.py", "copies": "5", "size": "3868", "license": "apache-2.0", "hash": 723616675521704000, "line_mean": 27.6518518519, "line_max": 86, "alpha_frac": 0.6483971044, "autogenerated": false, "ratio": 3.5067996373526746, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6655196741752675, "avg_score": null, "num_lines": null }
"""auth Revision ID: 140aa9118ff Revises: None Create Date: 2015-03-13 18:13 """ from alembic import op import sqlalchemy as sa from sqlalchemy_searchable import sync_trigger revision = '140aa9118ff' down_revision = None def upgrade(): conn = op.get_bind() op.create_table( 'users', sa.Column('name', sa.Unicode(), nullable=True), sa.Column('email', sa.Unicode(), nullable=True), sa.Column('search_vector', sa.TSVectorType(), nullable=True), sa.Column('locale', sa.String(length=16), nullable=True), sa.Column('tzinfo', sa.String(length=16), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('modified_at', sa.DateTime(), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('login', sa.Unicode(), nullable=False), sa.Column('password', sa.String(length=255), nullable=True), sa.Column('last_sign_in', sa.DateTime(), nullable=True), sa.Column('deleted', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=False) op.create_index(op.f('ix_users_login'), 'users', ['login'], unique=True) sync_trigger(conn, 'users', 'search_vector', ['name', 'email']) op.create_table( 'roles', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Unicode(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_table( 'users_roles', sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['role_id'], [u'roles.id'], ), sa.ForeignKeyConstraint(['user_id'], [u'users.id'], ) ) op.create_index(op.f('ix_users_roles_role_id'), 'users_roles', ['role_id'], unique=False) op.create_index(op.f('ix_users_roles_user_id'), 'users_roles', ['user_id'], unique=False) def downgrade(): op.drop_index(op.f('ix_users_roles_user_id'), table_name='users_roles') op.drop_index(op.f('ix_users_roles_role_id'), table_name='users_roles') op.drop_table('users_roles') op.drop_table('roles') op.drop_index(op.f('ix_users_login'), table_name='users') op.drop_index(op.f('ix_users_email'), table_name='users') op.drop_table('users')
{ "repo_name": "lucuma/vd-flask", "path": "migrations/versions/20150313-18-13_140aa9118ff_auth.py", "copies": "1", "size": "2416", "license": "bsd-3-clause", "hash": -4919639636854227000, "line_mean": 37.3492063492, "line_max": 93, "alpha_frac": 0.6233443709, "autogenerated": false, "ratio": 3.2737127371273713, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4397057108027371, "avg_score": null, "num_lines": null }
"""auth Revision ID: cd454cecb6e8 Revises: 5cbf5ac4455e Create Date: 2017-04-26 16:41:11.797947 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'cd454cecb6e8' down_revision = '5cbf5ac4455e' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('role', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=80), nullable=False), sa.Column('description', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name'), schema='public' ) op.create_table('user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('password', sa.String(length=255), nullable=False), sa.Column('email', sa.String(length=255), nullable=False), sa.Column('active', sa.Boolean(), nullable=True), sa.Column('name', sa.String(length=40), nullable=False), sa.Column('surname', sa.String(length=40), nullable=False), sa.Column('lastName', sa.String(length=40), nullable=False), sa.Column('roleId', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['roleId'], ['public.role.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), schema='public' ) op.create_table('course', sa.Column('id', sa.String(length=32), nullable=False), sa.Column('name', sa.String(length=200), nullable=False), sa.Column('contents', sa.Text(), nullable=False), sa.Column('preface', sa.Text(), nullable=False), sa.Column('postTime', sa.DateTime(), nullable=False), sa.Column('authorId', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['authorId'], ['public.user.id'], ), sa.PrimaryKeyConstraint('id'), schema='public' ) op.create_table('roles_users', sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['role_id'], ['public.role.id'], ), sa.ForeignKeyConstraint(['user_id'], ['public.user.id'], ), schema='public' ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('roles_users', schema='public') op.drop_table('course', schema='public') op.drop_table('user', schema='public') op.drop_table('role', schema='public') # ### end Alembic commands ###
{ "repo_name": "dmitrijbozhkov/zno-library", "path": "server/src/alembic/versions/cd454cecb6e8_auth.py", "copies": "1", "size": "2472", "license": "apache-2.0", "hash": -8481260425220693000, "line_mean": 34.3142857143, "line_max": 67, "alpha_frac": 0.6553398058, "autogenerated": false, "ratio": 3.414364640883978, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9517204935817261, "avg_score": 0.010499902173343244, "num_lines": 70 }
"""authome URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from . import views handler404 = 'dev.views.page_not_found_view' handler500 = 'dev.views.error_view' handler403 = 'dev.views.permission_denied_view' handler400 = 'dev.views.bad_request_view' urlpatterns = [ url(r'^(?P<category>.*)/editor/', views.BoardEditor.as_view(), name='editor'), url(r'^(?P<category>.*)/(?P<pk>\d+)/$', views.BoardDetail.as_view(), name='detail'), url(r'^(?P<category>.*)/', views.BoardList.as_view(), name='list'), ]
{ "repo_name": "xncbf/authome", "path": "board/urls.py", "copies": "1", "size": "1129", "license": "mit", "hash": 6540956768685010000, "line_mean": 37.9310344828, "line_max": 88, "alpha_frac": 0.6829052259, "autogenerated": false, "ratio": 3.272463768115942, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9451354485769862, "avg_score": 0.0008029016492160039, "num_lines": 29 }
__author__ = '01' __author__ += "Binary" __author__ += "ZeroOne" __author__ += "Hooman" from scapy.layers.inet import * from scapy.all import * import threading import time import sys import os conf.route.resync() conf.verb = 0 def PacketAnalyze(Pck) : if((Pck.haslayer(IP)) and ((Pck.getlayer(IP).src == Target1_IP and Pck.getlayer(IP).dst == Target2_IP) or (Pck.getlayer(IP).src == Target2_IP and Pck.getlayer(IP).dst == Target1_IP))) : if((Pck.getlayer(IP).src == Target1_IP)) : if(Pck.haslayer(Raw)) : print "\nTarget 1 Sent : " + str(Pck.summary()) + " ==> " + str(Pck.getlayer(Raw)) else : print "\nTarget 1 Sent : " + str(Pck.summary()) elif((Pck.getlayer(IP).src == Target2_IP)) : if(Pck.haslayer(Raw)) : print "\nTarget 2 Sent : " + str(Pck.summary()) + " ==> " + str(Pck.getlayer(Raw)) else : print "\nTarget 2 Sent : " + str(Pck.summary()) def GetMAC(IPAddress) : MAC = subprocess.Popen(["arp", "-n", IPAddress], stdout=subprocess.PIPE) MAC = MAC.communicate()[0] MAC = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", MAC).groups()[0] return MAC def Sniff() : print "[*] Sniffing ..." sniff(iface="eth0", prn=PacketAnalyze) def MITM(VIP, DIP, VMAC, DMAC) : Sniff_Thread = threading.Thread(target=Sniff, args=()) Sniff_Thread.start() print "[*] ARP Poisoning ..." while(True) : sendp(Ether(dst=VMAC)/ARP(op=2, psrc=DIP, pdst=VIP, hwdst=VMAC)) sendp(Ether(dst=DMAC)/ARP(op=2, psrc=VIP, pdst=DIP, hwdst=DMAC)) time.sleep(1) if __name__ == "__main__" : print "[+] Welcome" Banner = ''' 000 0 0 0 01 1 0 1 0 1 1 0 1 1 1 0 1 1 0 0 1 000 10001 ======================================================= 00000 1 1 100001 0000 1 0 00000 1 00000 0 0 1 1 1 1 1 0 1 1 1 1 0 0 00000 00000 0 1 0 1 1 1 1 0 1 1 0 0 1 00000 0 1 1 1 1 1 1 1 0 1 1 0 0 1 1 00000 100001 0000 100001 1 0 0 1 1 ''' print Banner if(len(sys.argv) != 3): print "[-] Usage : " + sys.argv[0] + " <Target_1 IPAddress> <Target_2 IPAddress>" exit(0) os.system("echo 1 > /proc/sys/net/ipv4/ip_forward") Target1_IP = sys.argv[1] Target2_IP = sys.argv[2] Target1_MAC = GetMAC(Target1_IP) Target2_MAC = GetMAC(Target2_IP) MITM(Target1_IP, Target2_IP, Target1_MAC, Target2_MAC)
{ "repo_name": "Hooman01/RemoteSniffer", "path": "Main.py", "copies": "1", "size": "2674", "license": "unlicense", "hash": -2506831773551676000, "line_mean": 24.4666666667, "line_max": 189, "alpha_frac": 0.5044876589, "autogenerated": false, "ratio": 2.7883211678832116, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8741856534436916, "avg_score": 0.01019045846925906, "num_lines": 105 }
__author__ = '116_13' from tkinter import * import time tk = Tk() tk.title('계산기') tk.resizable(0,0) #tk.wm_attributes("-topmost",1) canvas = Canvas(tk,width = 340,height = 620, bd = 0, highlightthickness = 0) canvas.pack() canvas.create_rectangle(0,0,340,620, fill = '#1f1f1f') #검정 배경색 canvas.create_rectangle(0,0,340,200,fill = '#f5b613') #주황?노랑? 배경색 def error_1(): bbb = Toplevel(canvas) button = Button(bbb, text = '입력값 초과') #버튼 설정 button.pack() def Circle(x1,y1,n,c): x2 = x1 + 60 y2 = y1 + 60 canvas.create_oval(x1, y1, x2, y2, fill = n, outline = c) class Number: def __init__(self,text_size): self.a = 0 self.n = 0 self.p = 0 self.f = 1 self.z = 0 self.r = 0 def click(event): if self.a >= 16: error_1() #error_1버튼 불러오기 canvas.create_rectangle(0,0,340,200,fill = '#f5b613') self.a = 0 self.n = 0 self.p = 0 self.f = 1 self.z = 0 self.r = 0 #주황네모 덮어 씌우고 모든 변수 초기화 else: if event.y >= 460 and event.y <= 520: if event.x >= 20 and event.x <= 80: if self.n !=0 and self.z == 0 and self.r == 0: #숫자 있을때 ex) 100000 처럼 0계속 찍힐 수 있음 #z는 처음 0뒤로 계속 찍히는 것 방지 - (1)오류 #여기서의 0은 뒤에도 0이 계속 올 수 있으므로 z+1을 안함 canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if self.n == 0 and self.z == 0 and self.r == 0: #숫자 없고 0이 찍힌적 없음(처음 0을 출력) canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.z = self.z + 1#0이 두번연속으로 안찍히게 self.a = self.a + 1 self.n = self.n + 1#부호 출력 가능해야 하기 때문 ex) 0+3... , (1)처음 0인데 숫자 취급 됨 if self.r == 1: #소수점 찍힘 canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.a = self.a + 1 #self.n = self.n+1 0.0다음에 부호 출력 방지(숫자 취급X) if event.x >= 100 and event.x <= 160: if self.n == 0 and self.z == 0 and self.r ==0: #처음에 0이 없고 78.00이런경우 self.z는 0이며 n또한 0이라 0이 3개씩 출력 #숫자 없고 0이 찍힌적 없음(처음 0을 출력) canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.z = self.z + 1#0이 두번연속으로 안찍히게 self.a = self.a + 1 self.n = self.n + 1#부호 출력 가능해야 하기 때문 ex) 0+3. if self.n != 0 and self.z == 0 and self.r == 0: #점이 안찍힐 경우, 없으면 self.r == 1: 도 만족해서 0이 4개씩 출력 canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.a = self.a + 1 canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 #0에서의 z와 마찬가지 if self.r == 1: #점이 찍혔을 때 canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.a = self.a + 1 canvas.create_text(20 + self.a*(text_size-5), 20, text = '0', font = ('', text_size)) self.a = self.a + 1 if event.x >= 180 and event.x <= 240: if self.n != 0 and self.r == 0: #숫자가 있을 때 canvas.create_text(20 + self.a*(text_size-5), 20, text = '.', font = ('', text_size)) self.a = self.a + 1 self.r = self.r +1 #숫자.숫자.숫자....방지 self.n = 0 #뒤에 부호 출력 방지, 다시 점찍히는거 방지 if event.x >= 260 and event.x <= 320: if self.n != 0: canvas.create_text(20 + self.a*(text_size-5), 20, text = '+', font = ('', text_size)) self.a = self.a + 1 self.n = 0 #부호 연속 출력 방지 self.r = 0 #소수점 출력 문제 방지 self.z = 0 if event.y >= 380 and event.y <= 440: if event.x >= 20 and event.x <= 80 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '7', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if event.x >= 100 and event.x <= 160 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '8', font = ('', text_size)) self.a = self.a + 1 self.n = self.n +1 if event.x >= 180 and event.x <= 240: canvas.create_text(20 + self.a*(text_size-5), 20, text = '9', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if event.x >= 260 and event.x <= 320: if self.n != 0 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '-', font = ('', text_size)) self.a = self.a + 1 self.n = 0 self.r = 0 self.z = 0#********* if self.a == 0: #처음 찍힐때 canvas.create_text(20 + self.a*(text_size-5), 20, text = '-', font = ('', text_size)) self.a = self.a +1 #0.0 후에 - 출력 가능(2) if event.y >= 300 and event.y <= 360: if event.x >= 20 and event.x <= 80 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '4', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if event.x >= 100 and event.x <= 160 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '5', font = ('', text_size)) self.a = self.a + 1 self.n = self.n +1 if event.x >= 180 and event.x <= 240: canvas.create_text(20 + self.a*(text_size-5), 20, text = '6', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if event.x >= 260 and event.x <= 320: if self.n != 0 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '×', font = ('', text_size)) self.a = self.a + 1 self.n = 0 self.r = 0 self.z = 0#********* if event.y >= 220 and event.y <= 280: if event.x >= 20 and event.x <= 80: canvas.create_text(20 + self.a*(text_size-5), 20, text = '1', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if event.x >= 100 and event.x <= 160 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '2', font = ('', text_size)) self.a = self.a + 1 self.n = self.n +1 if event.x >= 180 and event.x <= 240: canvas.create_text(20 + self.a*(text_size-5), 20, text = '3', font = ('', text_size)) self.a = self.a + 1 self.n = self.n + 1 if event.x >= 260 and event.x <= 320: if self.n != 0 : canvas.create_text(20 + self.a*(text_size-5), 20, text = '÷', font = ('', text_size)) self.a = self.a + 1 self.n = 0 self.r = 0 self.z = 0#********* if event.y >= 540 and event.y <= 620: if event.x >= 20 and event.x <= 80 : canvas.create_rectangle(0,0,340,200,fill = '#f5b613') self.a = 0 self.n = 0 self.p = 0 self.f = 1 self.z = 0 self.r = 0 canvas.bind("<Button-1>", click) canvas.pack() click = Number(25) c1 = '#1a1a1a' c2 = '#707070' c3 = '#2f2f2f' #canvas.create_rectangle(7,0,32,40) #canvas.create_rectangle(32,0,57,40) #canvas.create_rectangle(57,0,82,40) m = 20 for a in range(0,3): n = 220 number = Circle(m,n,c1,c2) for b in range(0,4): number = Circle(m,n,c1,c2) n += 80 m += 80 x = 260 y = 220 for c in range(0,4): ddd = Circle(x,y,c3,c2) y = y + 80 x = 20 y = 540 for c in range(0,3): ddd = Circle(x,y,c3,c2) x = x+80 p = 1 y = 250 for d in range(0,3): x = 50 canvas.create_text(x, y, text = p, fill = 'white', font = ('',25)) for e in range(0,3): canvas.create_text(x, y, text = p, fill = 'white', font = ('',25)) p += 1 x = x + 80 y = y+80 equal = Circle(260,540,c1,'#f5b613') canvas.create_text(50, 490, text = '0', fill = 'white', font = ('',25)) canvas.create_text(210, 480, text = '.', fill = 'white', font = ('',45)) canvas.create_text(130, 490, text = '00', fill = 'white', font = ('',25)) canvas.create_text(290, 250, text = '÷', fill = 'white', font = ('',25)) canvas.create_text(290, 330, text = '×', fill = 'white', font = ('',25)) canvas.create_text(290, 410, text = '-', fill = 'white', font = ('',25)) canvas.create_text(290, 490, text = '+', fill = 'white', font = ('',25)) canvas.create_text(50, 570, text = 'AC', fill = 'white', font = ('',25)) canvas.create_text(290, 570, text = '=', fill = '#f5b613', font = ('',25)) tk.mainloop()
{ "repo_name": "saintdragon2/python-3-lecture-2015", "path": "sinsojael_final/2nd_presentation/2조/calc_2.py", "copies": "1", "size": "11631", "license": "mit", "hash": -8781168408872996000, "line_mean": 41.3153846154, "line_max": 113, "alpha_frac": 0.3787837469, "autogenerated": false, "ratio": 2.9612382234185732, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.873516246427753, "avg_score": 0.020971901208208316, "num_lines": 260 }
__author__ = '116_24' import pygame import sys import time from pygame.locals import * import random import math import entities pygame.init() mainClock = pygame.time.Clock() windowSurface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption('Dungeon Sam is pretty damn cool v0.9, 10/16/11') white = (255, 255, 255) black = (0, 0, 0) windowSurface.fill(white) #Load/ define images here hero = pygame.Rect(300, 100, 30, 33)#hero-the-rectangle must have the same co-ordinates as heroStretchedImage heroImage = pygame.image.load('hero.png') heroStrechedImage = pygame.transform.scale(heroImage,(30, 33)) wall = pygame.Rect(250, 200, 38, 38) wallImage = pygame.image.load('Wall.png') enemy = pygame.Rect(150, 350, 38, 38) enemyImage = pygame.image.load('enemy.png') powerUp = pygame.Rect(100, 100, 21, 21)#power up, may be removed, just an idea that is easy to make powerUpImage = pygame.image.load('Diamond.png') arrowImage = pygame.image.load('arrowUp.png') swordImage = pygame.image.load('Sword.png') HP = pygame.font.SysFont(None, 20).render('HP', False, black,)#Draw "HP" on the screen(not really, "blit" is the one that does it) #Define Variables here HpRedContent = 0 #hpredcontent is the amount of red is in the hp bar. It makes the hpbar slide from green to red HpGreenContent = 255 HpRect = HP.get_rect() blit = False heroHp = 200 monsterHp = 50 arrowBlit = False ARROWMOVESPEED = 5 enemyBlit = True swordBlit = False shifty = False lifetime = 0 onScreen = False #Define Objects here #static object, doesn't do much yet... class Static(object): """base class for solid non-moving objects such as walls""" def __init__(self, image, name): self.name = name self.image = image self.x = self.image.x self.y = self.image.y class weapon(object): """Arrow""" def shoot(self, direction): if direction == "Left": arrow.move_ip(-1 * ARROWMOVESPEED, 0) if direction == "Right": arrow.move_ip(ARROWMOVESPEED, 0) if direction == "Up": arrow.move_ip(0, -1 * ARROWMOVESPEED) if direction == "Down": arrow.move_ip(0, ARROWMOVESPEED) def getRatio (self, A, B, AMS):#AMS means arrowmovespeed self.__ratio = AMS / math.sqrt(A * A + B * B) def getXY (self, A, B): self.__X = self.__ratio * A self.__Y = self.__ratio * B def getNextX(self, heroX): NextX = heroX + self.__X return NextX def getNextY(self, heroY): NextY = heroY + self.__Y return NextY class melee(weapon): """Sword""" def __init__(self): lifetime = 0 def slash(self, direction): if direction == "Left": arrow.move_ip(-1 * ARROWMOVESPEED, 0) if direction == "Right": arrow.move_ip(ARROWMOVESPEED, 0) if direction == "Up": arrow.move_ip(0, -1 * ARROWMOVESPEED) if direction == "Down": arrow.move_ip(0, ARROWMOVESPEED) player = entities.Hero(hero, 'Bob', heroHp) monster1 = entities.Monster(enemy, 'joe', monsterHp) MOVESPEED = 2 staticWall = Static(wall, 'wall') #mainloop...program actually runs here while player.Hp > 0: # DON"T DELETE THE WHILE LOOP for event in pygame.event.get():#detects events if event.type == QUIT:#if the "X" button is pressed in top right pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT or event.key == ord('a'): player.moving = True player.movingLeft = True player.movingRight = False if event.key == K_RIGHT or event.key == ord('d'): player.moving = True player.movingRight = True player.movingLeft = False if event.key == K_UP or event.key == ord('w'): player.moving = True player.movingUp = True player.movingDown = False if event.key == K_DOWN or event.key == ord('s'): player.moving = True player.movingUp = False player.movingDown = True if event.key == K_x: pygame.quit() sys.exit() if event.key == K_LSHIFT: shifty = True if event.type == KEYUP: if event.key == K_UP or event.key == ord('w'): # WASD!! player.moving = False player.movingUp = False if event.key == K_DOWN or event.key == ord('s'): player.moving = False player.movingDown = False if event.key == K_LEFT or event.key == ord('a'): player.moving = False player.movingLeft = False if event.key == K_RIGHT or event.key == ord('d'): player.moving = False player.movingRight = False if event.key == K_LSHIFT: shifty = False if event.type == MOUSEBUTTONDOWN and shifty == False:#ARROWS ARROWS ARROWS ARROWS ARROWS xDelta = event.pos[0] - hero.centerx yDelta = event.pos[1] - hero.centery arrow = pygame.Rect(hero.centerx, hero.centery, 9, 14) newArrow = weapon() newArrow.getRatio(xDelta, yDelta, 10) newArrow.getXY(xDelta, yDelta) arrowBlit = True if event.type == MOUSEBUTTONDOWN and shifty == True:#SWORDS SWORDS SWORDS SWORDS SWORDS xDelta = event.pos[0] - hero.centerx yDelta = event.pos[1] - hero.centery sword = pygame.Rect(hero.centerx, hero.centery, 9, 14) newSword = melee() newSword.getRatio(xDelta, yDelta, 10) newSword.getXY(xDelta, yDelta) swordBlit = True onScreen = True if onScreen == True: lifetime += 1 if lifetime >= 4 and swordBlit == True: swordBlit = False onScreen = False lifetime = 0 # Move arrow and update arrows if arrowBlit == True: arrow.centerx = newArrow.getNextX(arrow.centerx) arrow.centery = newArrow.getNextY(arrow.centery) if arrowBlit == True and arrow.colliderect(enemy): monster1.Hp -= 1 #arrow does 1 damage if monster1.Hp == 0: enemyBlit == False #Move and update swords if swordBlit == True and lifetime < 4 and lifetime != 0: sword.centerx = newSword.getNextX(sword.centerx) sword.centery = newSword.getNextY(sword.centery) if swordBlit == True and sword.colliderect(enemy): monster1.Hp -= 1 #arrow does 1 damage if monster1.Hp < 0: enemyBlit == False player.getOldX() #calls on players moving methods if player.movingLeft == True and player.image.left > 0: player.moveLeft(MOVESPEED) if player.movingRight == True and player.image.right < 500: player.moveRight(MOVESPEED) if player.movingUp == True and player.image.top > 0: player.moveUp(MOVESPEED) if player.movingDown == True and player.image.bottom < 400: player.moveDown(MOVESPEED) windowSurface.fill(white) if player.image.colliderect(wall): player.collideWall() if player.image.colliderect(enemy): player.takeDamage(HpRedContent, HpGreenContent) HpRedContent = player.newRed HpGreenContent = player.newGreen Here is the entities module: import pygame import sys from pygame.locals import* hero = pygame.Rect(300, 100, 30, 33)#hero-the-rectangle must have the same co-ordinates as heroStretchedImage heroImage = pygame.image.load('hero.png') heroStrechedImage = pygame.transform.scale(heroImage,(30, 33)) enemy = pygame.Rect(150, 350, 38, 38) enemyImage = pygame.image.load('enemy.png') #Entity object - all moving things(player, monsters, arrow) will be derived from this class Entity(object): """Entity""" #reintroduced moving; thought it would be useful moving = False movingLeft = False movingRight = False movingUp = False movingDown = False def __init__(self, image, name, Hp): self.name = name self.image = image self.Hp = Hp self.x = self.image.x self.y = self.image.y self.location = (self.x, self.y) self.newRed = 0 self.newGreen = self.Hp + 55 #moving methods def moveLeft(self, Xspeed): self.image.left -= Xspeed def moveRight(self, Xspeed): self.image.right += Xspeed def moveUp(self, Yspeed): self.image.top -= Yspeed def moveDown(self, Yspeed): self.image.bottom += Yspeed def takeDamage(amount): pass #Hero object(what the player is) class Hero(Entity): """Hero""" inventory = [] oldX = None oldY = None def getOldX(self): self.oldX = self.image.left self.oldY = self.image.top def heroDie(self): pygame.quit() sys.exit() def collideWall(self): self.image.left = self.oldX self.image.top = self.oldY def takeDamage(self, RedContent, GreenContent): self.Hp -= 1 self.newRed += 1 self.newGreen = self.Hp class Monster(Entity): """MONSTER"""
{ "repo_name": "saintdragon2/python-3-lecture-2015", "path": "civil_mid_mid/hwaa.py", "copies": "1", "size": "8713", "license": "mit", "hash": 8907037313934475000, "line_mean": 28.1404682274, "line_max": 130, "alpha_frac": 0.6403075864, "autogenerated": false, "ratio": 3.2151291512915128, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43554367376915126, "avg_score": null, "num_lines": null }
__author__ = '1' from model.address import Address import re class AddressHelper: def __init__(self, app): self.app = app def open_address_page(self): wd = self.app.wd if not (wd.current_url.endswith("http://localhost/addressbook/") and len(wd.find_elements_by_name("Send e-Mail")) > 0): self.app.open_home_page() def fill_address_form(self, data): wd = self.app.wd wd.find_element_by_name("firstname").click() wd.find_element_by_name("firstname").clear() wd.find_element_by_name("firstname").send_keys(data.name) wd.find_element_by_name("middlename").click() wd.find_element_by_name("middlename").clear() wd.find_element_by_name("middlename").send_keys(data.middlename) wd.find_element_by_name("lastname").click() wd.find_element_by_name("lastname").clear() wd.find_element_by_name("lastname").send_keys(data.lastname) wd.find_element_by_name("nickname").click() wd.find_element_by_name("nickname").clear() wd.find_element_by_name("nickname").send_keys(data.nickname) wd.find_element_by_name("company").click() wd.find_element_by_name("company").clear() wd.find_element_by_name("company").send_keys(data.company) wd.find_element_by_name("home").click() wd.find_element_by_name("home").clear() wd.find_element_by_name("home").send_keys(data.phone) def create(self, data): wd = self.app.wd # init adress creation wd.find_element_by_link_text("add new").click() self.fill_address_form(data) # submit adress creation wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() self.open_address_page() self.address_cache = None def select_address_by_index(self, index): wd = self.app.wd wd.find_elements_by_name("selected[]")[index].click() def select_address_by_id(self, id): wd = self.app.wd wd.find_element_by_css_selector("input[value='%s']" % id).click() def delete_address_by_index(self, index): wd = self.app.wd # open groups page self.open_address_page() self.select_address_by_index(index) # submit deletion wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click() wd.switch_to_alert().accept() self.open_address_page() self.address_cache = None def delete_address_by_id(self, id): wd = self.app.wd # open groups page self.open_address_page() self.select_address_by_id(id) # submit deletion wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click() wd.switch_to_alert().accept() self.open_address_page() self.address_cache = None def delete_first_address(self): self.delete_address_by_index(0) def change_field_value(self,field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def open_address_by_index(self,index): wd = self.app.wd # init adress creation return wd.find_elements_by_css_selector('img[alt="Edit"]')[index].click() def edit_address_by_index(self, index, data): wd = self.app.wd # init adress creation wd.find_elements_by_css_selector('img[alt="Edit"]')[index].click() # fill form self.change_field_value("firstname",data.name) self.change_field_value("middlename",data.middlename) self.change_field_value("lastname",data.lastname) self.change_field_value("nickname",data.nickname) self.change_field_value("company",data.company) self.change_field_value("home",data.phone) # submit adress creation wd.find_element_by_xpath("//div[@id='content']/form[1]/input[22]").click() self.open_address_page() self.address_cache = None def edit_address_by_id(self, id, data): wd = self.app.wd # init adress creation wd.find_element_by_xpath("//a[@href='edit.php?id=%s']/img" % id).click() # fill form self.change_field_value("firstname",data.name) self.change_field_value("middlename",data.middlename) self.change_field_value("lastname",data.lastname) self.change_field_value("nickname",data.nickname) self.change_field_value("company",data.company) self.change_field_value("home",data.phone) # submit adress creation wd.find_element_by_xpath("//div[@id='content']/form[1]/input[22]").click() self.open_address_page() self.address_cache = None def edit_first_address(self, data): self.edit_address_by_index(0) def count(self): wd = self.app.wd return len(wd.find_elements_by_name("selected[]")) address_cache = None def get_address_list(self): if self.address_cache is None: wd = self.app.wd self.open_address_page() self.address_cache = [] for element in wd.find_elements_by_xpath("//div[1]/div[4]/form[2]/table/tbody/tr[@name='entry']"): cells = element.find_elements_by_tag_name("td") name = cells[2].text lastname = cells[1].text address = cells[3].text id = cells[0].find_element_by_tag_name("input").get_attribute("value") all_phones = cells[5].text all_emails = cells[4].text self.address_cache.append(Address(name=name, lastname=lastname, id=id, address=address, all_phones_from_home_page=all_phones, all_emails_from_home_page=all_emails)) return list(self.address_cache) def get_address_info_from_edit_page(self, index): wd = self.app.wd self.open_address_to_edit_by_index(index) name = wd.find_element_by_name("firstname").get_attribute("value") middlename = wd.find_element_by_name("middlename").get_attribute("value") lastname = wd.find_element_by_name("lastname").get_attribute("value") company = wd.find_element_by_name("company").get_attribute("value") nickname = wd.find_element_by_name("nickname").get_attribute("value") address = wd.find_element_by_name("address").get_attribute("value") id = wd.find_element_by_name("id").get_attribute("value") email = wd.find_element_by_name("email").get_attribute("value") email2 = wd.find_element_by_name("email2").get_attribute("value") email3 = wd.find_element_by_name("email3").get_attribute("value") phone = wd.find_element_by_name("home").get_attribute("value") mobilephone = wd.find_element_by_name("mobile").get_attribute("value") workphone = wd.find_element_by_name("work").get_attribute("value") secondaryphone = wd.find_element_by_name("phone2").get_attribute("value") return Address(name=name, middlename=middlename,lastname=lastname,address=address, id=id, company=company,nickname=nickname, phone=phone, mobilephone=mobilephone,workphone=workphone,secondaryphone=secondaryphone, email=email, email2=email2, email3=email3) def open_address_to_edit_by_index(self, index): wd = self.app.wd self.open_address_page() row = wd.find_elements_by_name("entry")[index] cell = row.find_elements_by_tag_name("td")[7] cell.find_element_by_tag_name("a").click() def open_address_view_by_index(self, index): wd = self.app.wd self.open_address_page() row = wd.find_elements_by_name("entry")[index] cell = row.find_elements_by_tag_name("td")[6] cell.find_element_by_tag_name("a").click() def get_address_from_view_page(self, index): wd = self.app.wd self.open_address_view_by_index(index) text = wd.find_element_by_id("content").text return Address(all_fields=text)
{ "repo_name": "liliasapurina/python_training", "path": "fixture/address.py", "copies": "1", "size": "8345", "license": "apache-2.0", "hash": -3074819857100079600, "line_mean": 42.6963350785, "line_max": 127, "alpha_frac": 0.6027561414, "autogenerated": false, "ratio": 3.509251471825063, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46120076132250626, "avg_score": null, "num_lines": null }
__author__ = '1' from model.group import Group class GroupHelper: def __init__(self, app): self.app = app def open_group_page(self): wd = self.app.wd if not (wd.current_url.endswith("/group.php") and len(wd.find_elements_by_name("new")) > 0): wd.find_element_by_link_text("groups").click() def fill_group_form(self, group_data): wd = self.app.wd wd.find_element_by_name("group_name").click() wd.find_element_by_name("group_name").clear() wd.find_element_by_name("group_name").send_keys(group_data.name) wd.find_element_by_name("group_header").click() wd.find_element_by_name("group_header").clear() wd.find_element_by_name("group_header").send_keys(group_data.header) wd.find_element_by_name("group_footer").click() wd.find_element_by_name("group_footer").clear() wd.find_element_by_name("group_footer").send_keys(group_data.footer) def create(self, group_data): wd = self.app.wd # open groups page self.open_group_page() # init group creation wd.find_element_by_name("new").click() self.fill_group_form(group_data) # submit group creation wd.find_element_by_name("submit").click() wd.find_element_by_css_selector("div.msgbox").click() # return to groups page self.return_to_groups_page() self.group_cache = None def select_group_by_index(self, index): wd = self.app.wd wd.find_elements_by_name("selected[]")[index].click() def select_group_by_id(self, id): wd = self.app.wd wd.find_element_by_css_selector("input[value='%s']" % id).click() def delete_group_by_index(self, index): wd = self.app.wd # open groups page self.open_group_page() self.select_group_by_index(index) # submit deletion wd.find_element_by_name("delete").click() self.return_to_groups_page() self.group_cache = None def delete_group_by_id(self, id): wd = self.app.wd # open groups page self.open_group_page() self.select_group_by_id(id) # submit deletion wd.find_element_by_name("delete").click() self.return_to_groups_page() self.group_cache = None def delete_first_group(self): self.delete_group_by_index(0) def change_field_value(self,field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(field_name).clear() wd.find_element_by_name(field_name).send_keys(text) def edit_group_by_index(self, index, new_group_data): wd = self.app.wd # open groups page self.open_group_page() self.select_group_by_index(index) # submit edition wd.find_element_by_name("edit").click() # make editions self.change_field_value("group_name",new_group_data.name) self.change_field_value("group_header",new_group_data.header) self.change_field_value("group_footer",new_group_data.footer) # submit group update wd.find_element_by_name("update").click() self.return_to_groups_page() self.group_cache = None def edit_group_by_id(self, id, new_group_data): wd = self.app.wd # open groups page self.open_group_page() self.select_group_by_id(id) # submit edition wd.find_element_by_name("edit").click() # make editions self.change_field_value("group_name",new_group_data.name) self.change_field_value("group_header",new_group_data.header) self.change_field_value("group_footer",new_group_data.footer) # submit group update wd.find_element_by_name("update").click() self.return_to_groups_page() self.group_cache = None def edit_first_group(self, new_group_data): self.edit_group_by_index(0) def return_to_groups_page(self): wd = self.app.wd wd.find_element_by_link_text("group page").click() def count(self): wd = self.app.wd self.open_group_page() return len(wd.find_elements_by_name("selected[]")) group_cache = None def get_group_list(self): if self.group_cache is None: wd = self.app.wd self.open_group_page() self.group_cache = [] for element in wd.find_elements_by_css_selector("span.group"): text = element.text id = element.find_element_by_name("selected[]").get_attribute("value") self.group_cache.append(Group(name=text,id=id)) return list(self.group_cache)
{ "repo_name": "liliasapurina/python_training", "path": "fixture/group.py", "copies": "1", "size": "4782", "license": "apache-2.0", "hash": -3402304160222706000, "line_mean": 34.962406015, "line_max": 100, "alpha_frac": 0.5972396487, "autogenerated": false, "ratio": 3.4132762312633833, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9502104880732929, "avg_score": 0.0016821998460910593, "num_lines": 133 }
__author__ = '1' from model.project import Project class ProjectHelper: def __init__(self, app): self.app = app def open_projects_page(self): wd = self.app.wd # open manage page wd.find_element_by_xpath("//html/body/table[2]/tbody/tr/td[1]/a[7]").click() #find_element_by_xpath('//div/td[1]') # opem projects manage page wd.find_element_by_xpath("//html/body/div[2]/p/span[2]/a").click() def create(self, project): wd = self.app.wd # open "manage projects" self.open_projects_page() # press "create new project" wd.find_element_by_css_selector("body > table:nth-child(6) > tbody > tr:nth-child(1) > td > form > input.button-small").click() # fill project form wd.find_element_by_name("name").click() wd.find_element_by_name("name").clear() wd.find_element_by_name("name").send_keys(project.name) wd.find_element_by_name("description").click() wd.find_element_by_name("description").clear() wd.find_element_by_name("description").send_keys(project.description) # submit group creation wd.find_element_by_css_selector("body > div:nth-child(6) > form > table > tbody > tr:nth-child(7) > td > input").click() def get_project_list(self): wd = self.app.wd self.open_projects_page() projects = [] for element in wd.find_elements_by_xpath("/html/body/table[3]/tbody/tr"): text = element.text id = element.get_attribute("value") projects.append(Project(name=text,id=id)) return projects def select_project_by_index(self, index): wd = self.app.wd wd.find_elements_by_xpath("/html/body/table[3]/tbody/tr/td[1]/a")[index].click() def delete_project_by_index(self, index): wd = self.app.wd # open groups page self.open_projects_page() self.select_project_by_index(index) # submit deletion wd.find_element_by_css_selector("body > div.border.center > form > input.button").click() # answer on second question about deleting wd.find_element_by_css_selector("body > div:nth-child(5) > form > input.button").click() def count(self): wd = self.app.wd self.open_projects_page() return len(wd.find_elements_by_xpath("/html/body/table[3]/tbody/tr"))
{ "repo_name": "liliasapurina/python_training_mantiss", "path": "fixture/project.py", "copies": "1", "size": "2412", "license": "apache-2.0", "hash": 7027408496536794000, "line_mean": 39.2, "line_max": 135, "alpha_frac": 0.6044776119, "autogenerated": false, "ratio": 3.4019746121297603, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.450645222402976, "avg_score": null, "num_lines": null }
__author__ = '1' from pony.orm import * from datetime import datetime from model.group import Group from model.address import Address from pymysql.converters import decoders class ORMFixture: db = Database() class ORMGroup(db.Entity): _table_ = "group_list" id = PrimaryKey(int, column = "group_id") name = Optional(str, column = "group_name") header = Optional(str, column = "group_header") footer = Optional(str, column = "group_footer") addresses = Set(lambda: ORMFixture.ORMAddress, table = "address_in_groups", column = "id", reverse = "groups", lazy = True) class ORMAddress(db.Entity): _table_ = "addressbook" id = PrimaryKey(int, column = "id") name = Optional(str, column = "firstname") lastname = Optional(str, column = "lastname") email = Optional(str, column = "email") email2 = Optional(str, column = "email2") email3 = Optional(str, column = "email3") mobilephone = Optional(str, column = "mobile") workphone = Optional(str, column = "work") phone = Optional(str, column = "home") secondaryphone = Optional(str, column = "phone2") address = Optional(str, column = "address") deprecated = Optional(datetime, column = "deprecated") groups = Set(lambda: ORMFixture.ORMGroup, table = "address_in_groups", column = "group_id", reverse = "addresses", lazy = True) def __init__(self, host, user, name, password): self.db.bind('mysql', host = host, database = name, user = user, password = password, conv = decoders) self.db.generate_mapping() def convert_groups_to_model(self, groups): def convert(group): return Group(id = str(group.id), name = group.name, header = group.header, footer = group.footer) return list(map(convert, groups)) @db_session def get_group_list(self): return self.convert_groups_to_model(select(g for g in ORMFixture.ORMGroup)) def convert_addresses_to_model(self, addresses): def convert(address): return Address(id = str(address.id), name = address.name, lastname = address.lastname, email = address.email,email2 = address.email2, email3 = address.email3, mobilephone = address.mobilephone, workphone = address.workphone, phone = address.phone, secondaryphone = address.secondaryphone, address = address.address) return list(map(convert, addresses)) @db_session def get_address_list(self): return self.convert_addresses_to_model(select(a for a in ORMFixture.ORMAddress if a.deprecated is None)) @db_session def get_address_in_group(self, group): orm_group = list(select(g for g in ORMFixture.ORMGroup if g.id == group.id))[0] return self.convert_addresses_to_model(orm_group.addresses) @db_session def get_address_not_in_group(self, group): orm_group = list(select(g for g in ORMFixture.ORMGroup if g.id == group.id))[0] return self.convert_addresses_to_model( select(a for a in ORMFixture.ORMAddress if a.deprecated is None and orm_group not in a.groups))
{ "repo_name": "liliasapurina/python_training", "path": "fixture/orm.py", "copies": "1", "size": "3210", "license": "apache-2.0", "hash": 3492404560571746000, "line_mean": 43.5972222222, "line_max": 149, "alpha_frac": 0.6429906542, "autogenerated": false, "ratio": 3.7943262411347516, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9846219949522235, "avg_score": 0.01821938916250343, "num_lines": 72 }
__author__ = '1' from sys import maxsize class Address: def __init__(self,name = None,middlename = None,lastname = None,nickname = None,company = None,address=None,id = None, phone = None,mobilephone = None,workphone = None,secondaryphone = None, all_phones_from_home_page = None,all_fields = None, email = None,email2 = None,email3 = None,all_emails_from_home_page=None): self.name = name self.phone = phone self.address = address self.mobilephone = mobilephone self.workphone = workphone self.secondaryphone = secondaryphone self.all_phones_from_home_page=all_phones_from_home_page self.all_fields = all_fields self.middlename = middlename self.lastname = lastname self.nickname = nickname self.company = company self.email = email self.email2 = email2 self.email3 = email3 self.all_emails_from_home_page=all_emails_from_home_page self.id = id def __repr__(self): return "%s:%s %s" % (self.id,self.name, self.lastname) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name and self.lastname == self.lastname def id_or_max(adr): if adr.id: return int(adr.id) else: return maxsize
{ "repo_name": "liliasapurina/python_training", "path": "model/address.py", "copies": "1", "size": "1411", "license": "apache-2.0", "hash": -4229967786991187000, "line_mean": 37.1351351351, "line_max": 138, "alpha_frac": 0.6031183558, "autogenerated": false, "ratio": 3.664935064935065, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9686933133895916, "avg_score": 0.01622405736782971, "num_lines": 37 }
__author__ = '1' from telnetlib import Telnet class JamesHelper: def __init__(self, app): self.app = app def ensure_user_exist(self, username, password): james_config = self.app.config["james"] session = JamesHelper.Session(james_config["host"], james_config["port"], james_config["username"], james_config["password"]) if session.is_urer_registred(username): session.reset_password(username, password) else: session.create_user(username, password) session.quit() class Session: def __init__(self, host, port, username, password): self.telnet = Telnet(host, port, 5) self.read_until("Login id:") self.write(username + "\n") self.read_until("Password:") self.write(password + "\n") self.read_until("Welcome root. HELP for a list of commands") def read_until(self, text): self.telnet.read_until(text.encode('ascii'), 5) def write(self, text): self.telnet.write(text.encode('ascii')) def is_urer_registred(self, username): self.write("verify %s\n" % username) res = self.telnet.expect([b"exists", b"does not exist"]) return res[0] == 0 def create_user(self, username, password): self.write("adduser %s %s\n" % (username, password)) self.read_until("User %s added" % username) def reset_password(self, username, password): self.write("setpassword %s %s\n" % (username, password)) self.read_until("Password for %s reset" % username) def quit(self): self.write("quit\n")
{ "repo_name": "liliasapurina/python_training_mantiss", "path": "fixture/james.py", "copies": "1", "size": "1707", "license": "apache-2.0", "hash": -8183776568483045000, "line_mean": 34.5833333333, "line_max": 133, "alpha_frac": 0.5776215583, "autogenerated": false, "ratio": 3.7933333333333334, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48709548916333334, "avg_score": null, "num_lines": null }
__author__ = '1' import mysql.connector from model.group import Group from model.address import Address class DbFixture: def __init__(self, host, user, name, password): self.host = host self.user = user self.name = name self.password = password self.connection = mysql.connector.connect(host = host, database = name, user = user, password = password) self.connection.autocommit = True def get_group_list(self): list = [] cursor = self.connection.cursor() try: cursor.execute("select group_id,group_name,group_header,group_footer from group_list") for row in cursor: (id, name, header, footer) = row list.append(Group(id=str(id),name=name,header=header,footer=footer)) finally: cursor.close() return list def get_address_list(self): list = [] cursor = self.connection.cursor() try: cursor.execute("select id,firstname,middlename,lastname,nickname,company,email,email2,email3,mobile,work,home,phone2,address from addressbook where deprecated='0000-00-00 00:00:00'") for row in cursor: (id,firstname,middlename,lastname,nickname,company,email,email2,email3,mobile,work,home,phone2,address) = row list.append(Address(id=str(id),name=firstname,lastname=lastname, email=email,email2=email2,email3=email3, mobilephone=mobile,workphone=work,phone=home,secondaryphone=phone2, address=address)) finally: cursor.close() return list def destroy(self): self.connection.close()
{ "repo_name": "liliasapurina/python_training", "path": "fixture/db.py", "copies": "1", "size": "1764", "license": "apache-2.0", "hash": -6711613908031418000, "line_mean": 39.1136363636, "line_max": 194, "alpha_frac": 0.6003401361, "autogenerated": false, "ratio": 4.180094786729858, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.010111379856620134, "num_lines": 44 }
__author__ = '1' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd # open home page self.app.open_home_page() # login wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys(username) wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys(password) wd.find_element_by_css_selector('input[type="submit"]').click() def is_logged_in(self): wd = self.app.wd return len(wd.find_elements_by_link_text("Logout")) > 0 def is_logged_in_as(self, username): wd = self.app.wd return self.get_logged_user() == username def get_logged_user(self): wd = self.app.wd return wd.find_element_by_xpath("//div/div[1]/form/b").text[1:-1] def logout(self): wd = self.app.wd wd.find_element_by_link_text("Logout").click() def ensure_logout(self): wd = self.app.wd if self.is_logged_in(): self.logout() def ensure_login(self, username, password): wd = self.app.wd if self.is_logged_in(): if self.is_logged_in_as(username): return else: self.logout() self.login(username, password)
{ "repo_name": "liliasapurina/python_training", "path": "fixture/session.py", "copies": "1", "size": "1458", "license": "apache-2.0", "hash": 1313394902257111800, "line_mean": 28.7755102041, "line_max": 73, "alpha_frac": 0.561042524, "autogenerated": false, "ratio": 3.390697674418605, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44517401984186045, "avg_score": null, "num_lines": null }
__author__ = '1' from model.address import Address import random import string import os.path import jsonpickle import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:],"n:f:",["number of groups","file"]) except getopt.GetoptError as err: getopt.usage() sys.exit(2) n = 5 f = "data/addresses.json" for o, a in opts: if o == "-n": n = int(a) elif o == "-f": f = a def random_string(prefix, maxlen): symbols = string.ascii_letters + string.digits + string.punctuation + " "*10 return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) def random_phone(maxlen): symbols = string.digits + "-"*4 + "+" + "("*2 + ")"*2 return "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) def random_email(maxlen): symbols = string.digits + "-"*4 + "+" + "("*2 + ")"*2 return "".join([random.choice(symbols) for i in range(random.randrange(maxlen/2))])+"@"+"".join([random.choice(symbols) for i in range(random.randrange(maxlen/2))]) testdata =[ Address(name="",lastname="",middlename="",nickname="",company="",phone="",mobilephone="",workphone="",secondaryphone="")] + [ Address(name=random_string("name",10),lastname=random_string("lastname",10),middlename=random_string("middlename",10), nickname=random_string("nickname",10),company=random_string("company",10), phone=random_phone(10),mobilephone=random_phone(15),workphone=random_phone(10),secondaryphone=random_phone(15), email=random_email(20),email2=random_email(20),email3=random_email(20), address=random_string("address",20)) for i in range(n) ] file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f) with open(file, "w") as out: jsonpickle.set_encoder_options("json", indent=2) out.write(jsonpickle.encode(testdata))
{ "repo_name": "liliasapurina/python_training", "path": "generator/address.py", "copies": "1", "size": "1885", "license": "apache-2.0", "hash": 1384795451396821800, "line_mean": 34.5660377358, "line_max": 168, "alpha_frac": 0.6525198939, "autogenerated": false, "ratio": 3.336283185840708, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4488803079740708, "avg_score": null, "num_lines": null }