def do_POST(self): ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) length = int(self.headers.getheader('content-length')) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) else: postvars = {} if self.path == '/Forms/login_security_1.html': auth = Auth() if auth.http_client_auth(postvars): credentials = auth.get_credentials() self.send_response(303) self.send_header('Location', '/rpSys.html') self.send_header('Set-Cookie', 'C0=' + credentials['user'] + '; path=/') self.send_header('Set-Cookie', 'C1=' + credentials['pass'] + '; path=/') self.end_headers() self.log_http(303, postvars) else: self.do_GET() self.log_http(200, postvars) else: self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.log_http(200, postvars)
def __nowOnlineResponse(self, senderObj, address): ''' __nowOnlineResponse(None): Input : None Output : Obj { } Message format {"message-type":"quiz", challange, hash{answer}} Purpose : When Client shows intent to connect Generate a challenge and send it to server ''' if senderObj["user"] in self.__authDict: self.__authDict.pop(senderObj["user"]) rand = os.urandom(100) t = randint(30000, 65536) sha = hashlib.sha256() sha.update(rand + str(t)) guess = sha.digest() self.__authDict[senderObj["user"]] = Auth(str(t)) response = [ pickle.dumps({ "message-type": "quiz", "challange": rand, "answer": guess }), address ] return response
def __authorize__(self): try: authorizer = Auth(Flow.__SCOPES, *Flow.__required_folders) service = authorizer.authorize() self.service = service except Exception as e: print(str(e)) sys.exit(-1)
def __init__(self, urlBase, name, token): self.name = name self.token = token self.urlBase = urlBase self.auth = Auth(self.token) self.header = [ Header("Content-Type", "Content-Type", "application/json", "text") ]
def authorizeStuff(self): auth = Auth('http', 'pfioh_config.cfg') allowed, error = auth.authorizeClientRequest(self.headers) print('\n\nAUTH: %s' % str(allowed)) if allowed: self.send_response(200, "Authentication Successful!") else: print('%s: %s %s' % error) self.send_error(error[0], error[1], error[2])
def grant_permission(file_id, email): authorizer = Auth(SCOPES, os.path.join(os.path.abspath('.'), './credentials'), os.path.join(os.path.abspath('.'), './pickled_creds')) service = authorizer.authorize() request_body = { 'type': 'user', 'role': 'reader', 'emailAddress': email } results = service.permissions().create(fileId=file_id, body=request_body, fields='emailAddress,id').execute() print(results)
def user(self): print('Choose option: \n 1.Register \t 2.Login') choice = input('Enter your choice :') auth = Auth() if choice == '1': auth.register() elif choice == '2': auth.login() else: print('Invalid choice') self.user()
def get_session(self): auth = Auth() credentials = auth.get_credentials() cookie = Cookie.SimpleCookie(self.headers.getheader('Cookie')) session = False if cookie.has_key('C0') and cookie.has_key('C1'): if cookie['C0'].value == credentials['user'] and cookie['C1'].value == credentials['pass']: session = True return session
def main(): authorizer = Auth(SCOPES, os.path.join(os.path.abspath('.'), './credentials'), os.path.join(os.path.abspath('.'), './pickled_creds')) service = authorizer.authorize() # Call the Drive v3 API results = service.files().list( fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id']))
def main(): parent_folder = get_folder_id_by_name(get_id_only=False) authorizer = Auth(SCOPES, os.path.join(os.path.abspath('.'), './credentials'), os.path.join(os.path.abspath('.'), './pickled_creds')) service = authorizer.authorize() with open(os.path.join(os.path.abspath('.'), './student_ids/students.json'), 'r') as students_id_file: # get the student ids student_ids = json.load(students_id_file) folder_prefix = input("Enter folder prefix: ") if folder_prefix != '': lower_limit = input("Are there existing folders? If so, enter the value of suffix to start from: ") if lower_limit != '': create_nested_folder_structure(service, parent_folder, folder_prefix, student_ids, folder_suffix_lower_limit=int(lower_limit)) else: create_nested_folder_structure(service, parent_folder, folder_prefix, student_ids) else: create_student_folders(service, student_ids, parent_folder)
def auth(): body = request.get_json() if body is None: return Response(status=400) user = body.get('username') passwd = body.get('password') if user is None or passwd is None: return Response(status=400) found_user = User.query.filter(User.username == user).first() if found_user is None: return Response(status=403) if Argon.check_password_hash(found_user.hsh, passwd + found_user.salt): auth = Auth() db_session.add(auth) db_session.commit() resp = Response(status=400) resp.headers["X-Auth-Token"] = auth.token return resp return Response(status=403)
def get_child_folders(): """ This is a function that takes the name of the folder as input, and then finds the subfolders under that folder """ authorizer = Auth(SCOPES, os.path.join(os.path.abspath('.'), './credentials'), os.path.join(os.path.abspath('.'), './pickled_creds')) service = authorizer.authorize() folder_id = get_folder_id_by_name(get_id_only=True) if folder_id: print(folder_id) child_folders = service.files().list( q= f"mimeType='application/vnd.google-apps.folder' and {folder_id} in parents", fields='nextPageToken, files(id, name)').execute() pprint(child_folders) return child_folders return None
def get_folder_id_by_name(get_id_only=False): # get authorization if not authorized authorizer = Auth(SCOPES, os.path.join(os.path.abspath('.'), './credentials'), os.path.join(os.path.abspath('.'), './pickled_creds')) service = authorizer.authorize() folder_name = input("Please enter the folder name to search for: ") response = service.files().list(q=f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}'", spaces='drive', fields='nextPageToken, files(id, name)').execute() items = response.get('files', []) if not items: print('No files found.') return None else: item = items[0] if get_id_only: folder_id = f"'{item['id']}'" return folder_id else: return item
import requests import json import socketio import base64 from scraping import scrapFnacLatestReleases from parsing import parseMessage from Auth import Auth auth = Auth("http://*****:*****@gmail.com", "password": "******" }) sio = socketio.Client() @sio.event def connect(): print("Bot connected") @sio.event def disconnect(): print("Bot disconnected") sio.emit("disconnect") @sio.event def newMessage(data): message = data["content"] if parseMessage(message) == "fnac": releases = scrapFnacLatestReleases(10)
from py_tdlib import Client, Pointer from py_tdlib.constructors import getMe from Auth import Auth from term import Term import os api_id = 717420 api_hash = "8446b305f854ca732ca78f83e0b2b0b7" tdjson = Pointer(os.getcwd() + "/lib/libtdjson.so") tdjson.verbosity(0) client = Client(tdjson) Auth(api_id, api_hash, client).phone() result = client.send(getMe()) Term(client).prompt(result.first_name + result.last_name)
def main(): """ This script deals with creating a nested folder structure Parent Folder |_ <Prefix> #1 |_ Student ID #1 |_ Student ID #2 |_ Student ID #3 |_ ... |_ <Prefix> #2 |_ Student ID #1 |_ Student ID #2 |_ Student ID #3 |_ ... |_ ... if prefix is not specified, it will create a folder structure like this Parent Folder |_ Student ID #1 |_ Student ID #2 |_ Student ID #3 |_ ... """ # potential issue if the user doesn't have these folders create_necessary_folders([ os.path.join(os.path.abspath('.'), 'credentials'), os.path.join(os.path.abspath('.'), 'pickled_creds') ]) # get authorization if not authorized authorizer = Auth(SCOPES, os.path.join(os.path.abspath('.'), 'credentials'), os.path.join(os.path.abspath('.'), 'pickled_creds')) service = authorizer.authorize() parent_folder_name = input("Enter parent folder name: ") # creates one folder with the given name parent_metadata = { 'name': parent_folder_name, 'mimeType': 'application/vnd.google-apps.folder' } parent_folder = service.files().create(body=parent_metadata, fields='id').execute() print( f"Parent folder {parent_folder_name} created with id={parent_folder.get('id')}" ) # read json file, where student ids are stored in an array form try: with open( os.path.join(os.path.abspath('.'), 'student_ids/students.json'), 'r') as students_id_file: # get the student ids student_ids = json.load(students_id_file) folder_prefix = input("Enter folder prefix: ") if folder_prefix != '': create_nested_folder_structure(service, parent_folder, folder_prefix, student_ids) else: create_student_folders(service, student_ids, parent_folder) except FileNotFoundError: print( "Please prepare a students.json file under the student_ids folder." )
"name": "S" } } } }) # # Faltan agregar campos # {u'username': u'AR_dibox_000100000004', u'apikey_ttl': u'2017-03-18T14:30:11.838Z', u'country': u'AR', u'source_ip': u'::1', u'idp': u'dibox', u'access': u'full', u'user_agent': u'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'} authorization = Auth({ "database": { "table": "Auth", "pk": "apikey", "schema": { "apikey": "S", "enabled": "N", "expiration": "N", "username": "******" } } }) @application.route('/v1/cams/', methods=['GET']) @application.route('/v1/cams', methods=['GET']) @cross_origin() def cams(): args = {} now = int(time()) cam_duration = 40 * 60 cam_start = 10 * 60
def __init__(self): Gtk.Window.__init__(self, title="Magic Mirror") self.state_list = [ "HOME", "WEATHER", "TIME", "QUOTE", "CALENDAR", "HELP", "INFO", "MIRROR" ] self.state = "" # Data classes which update from subscriber input_data = InputData() weather_data = WeatherData() quote_data = QuoteData() calendar_data = EventData() message_data = MessageData() home_data = HomeData() self.auth_data = AuthData() pin_data = PinData() # Screen objects that are cycled in the window self.home_screen = Home(weather_data, calendar_data, home_data, self.auth_data) self.auth_screen = Auth(self.auth_data, pin_data) self.weather_screen = Weather(weather_data) self.time_screen = TimeDate() self.message_screen = Messages(message_data) self.quote_screen = Quote(quote_data) self.calendar_screen = Calendar(calendar_data) self.help_screen = Help() self.info_screen = Info() self.mirror_screen = Mirror() # Starts the MQTT subscriber self.data_thread = threading.Thread(target=subscriber.run, args=([ input_data, weather_data, quote_data, calendar_data, home_data, self.auth_data, pin_data ], )) self.data_thread.daemon = True self.data_thread.start() # Updates the value on the screens in separate threads GObject.timeout_add(1000, self.auth_screen.update) GObject.timeout_add(1000, self.weather_screen.update_weather) GObject.timeout_add(1000, self.time_screen.update_clock) GObject.timeout_add(1000, self.quote_screen.update) GObject.timeout_add(1000, self.calendar_screen.update_events) GObject.timeout_add(1000, self.message_screen.update_screen) GObject.timeout_add(1000, self.home_screen.update_home) self.app_stack = Gtk.Stack() self.app_stack.set_transition_type( Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) self.app_stack.set_transition_duration(500) self.app_stack.add_named(self.auth_screen, "Auth") self.app_stack.add_named(self.home_screen, "Home") self.app_stack.add_named(self.weather_screen, "Weather") self.app_stack.add_named(self.time_screen, "Time") self.app_stack.add_named(self.message_screen, "Message") self.app_stack.add_named(self.quote_screen, "Quote") self.app_stack.add_named(self.calendar_screen, "Calendar") self.app_stack.add_named(self.help_screen, "Help") self.app_stack.add_named(self.info_screen, "Info") self.app_stack.add_named(self.mirror_screen, "Mirror") # Meant to add the default screen self.add(self.app_stack) self.fullscreen() self.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(255, 0, 255)) self.set_icon(IMG.iconpix)
from flask_basicauth import BasicAuth from dbhelper import dbhelper from forum import forum from thread import thread from post import post from Auth import Auth from helper import helper from user import user dbPath = "proj.db" app = Flask(__name__) basic_auth = Auth(app) @app.route("/forums", methods=['GET']) def getForums(): whereList = {} ilist = helper.getList(dbPath, forum, whereList) response = make_response(ilist.serialize(), 200) response.headers["Content-Type"] = "application/json" return response @app.route("/forums", methods=['POST']) @basic_auth.required def createForum():
print Addon.getAddonInfo('path') Addon_path = Addon.getAddonInfo('path').decode(sys.getfilesystemencoding()) print Addon_path icon = xbmc.translatePath(os.path.join(Addon_path, 'icon.png')) fcookies = xbmc.translatePath( os.path.join(Addon_path, r'resources', r'data', r'cookies.txt')) # load XML library sys.path.append(os.path.join(Addon_path, r'resources', r'lib')) #from BeautifulSoup import BeautifulSoup # load GUI from Auth import Auth import HTMLParser hpar = HTMLParser.HTMLParser() #h = int(sys.argv[1]) def showMessage(heading, message, times=3000): xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")' % (heading, message, times, icon)) #------------------------------------------------------------------------------- kwargs = {'Addon': Addon} au = Auth(**kwargs) if au.Authorize() == True: au.showMain() del au
def main(): try: auth = Auth() token = auth.get_access_token() sp = Spotify(token) artist = input("Please enter your favourite artist's name: ").lstrip( ).rstrip().lower() # If an invalid input, print error message and exit if not artist: print('Please enter a valid artist name.') sys.exit(1) # Get the spotify ID of artist artist_id = sp.get_artist_id(artist) # Get user's Spotify ID user_id = os.getenv('SPOTIFY_USER_ID') # Do necessary error check. If artist exists in Spotify, then continue with data if artist_id: # Get artists albums albums = sp.get_albums(artist_id, limit=MAX_ALBUM_LIMIT_SET_BY_SPOTIFY) # If there are albums, print them if albums: print() print('*' * FIFTY_TIMES) print(f'{artist.title()} - ALBUMS') print('*' * FIFTY_TIMES) for album in albums: print(album) print() # Get the top tracks of artists and if exists, print them top_tracks = sp.get_top_tracks( artist_id, market=DEFAULT_MARKET_COUNTRY_CODE) if top_tracks: print() print('*' * FIFTY_TIMES) print( f'{artist.title()} - Top tracks in {DEFAULT_MARKET_COUNTRY_CODE}' ) print('*' * FIFTY_TIMES) for track in top_tracks: print(track) print() # Get user's tracks (the tracks in the public playlists) my_tracks = sp.get_users_playlists_tracks(user_id) # Get the top tracks of artist which are in your collection. for track in my_tracks: for top_track in top_tracks: if track in top_track: print( f'You have {top_track} in your collection!' ) break print() else: print(f'No top tracks for {artist} in {market}') else: print(f'No albums found for {artist.title()}') else: print(f'No albums found for {artist.title()}') # Get your play lists. Print them if any. playlists = sp.get_users_playlists(user_id) if playlists: print() print('*' * FIFTY_TIMES) print('My Play lists') print('*' * FIFTY_TIMES) for name in playlists: print(name) print() else: print("You don't have any public play lists.") except Exception as ex: print(ex)
#time.sleep(0.5+random.random()) obj=get_gift_of_captain(roomid,capid) if obj['code']==0: Log.info(str(roomid)+" 获取亲密度 "+str(obj['data']['award_text'])) elif obj['code']==-403: #发现被封禁立刻终止 Log.info("疑似被封禁"+str(obj)) break else: Log.info("领取失败"+str(obj)) #随机延迟5-10秒 time.sleep(5+int(random.random()*10)) Log.info("\n======START======"+str(time.asctime())+"============\n") a=Auth() a.work() csrf = config['Token']['CSRF'] Log.info(str(csrf)) cookie = config['Token']['COOKIE'] Log.info(str(cookie)) capdone = json.load(open("done.json")) capdone2={} #capdone={} nhour=time.localtime().tm_hour nlevel=0
from Auth import Auth auth = Auth("auth_info.json") user_csv = open("student_info.csv", "r") user_csv.readline() for line in user_csv: split = line.split(",") username = split[2][1:-1] password = username[::-1] auth.create_user(username, password)
sys.path.append(sys.path[0] + "/Src") from Auth import Auth from Coin2Silver import Coin2Silver from GiftSend import GiftSend from Group import Group from Silver2Coin import Silver2Coin from Task import Task from Config import * from CaseJudger import CaseJudger from MainDailyTask import MainDailyTask from MatchTask import MatchTask # 初始化所有class Auth = Auth() CaseJudger = CaseJudger() Coin2Silver = Coin2Silver() GiftSend = GiftSend() Group = Group() Silver2Coin = Silver2Coin() Task = Task() MainDailyTask = MainDailyTask() MatchTask = MatchTask() async def main(): daily_tasks = [ CaseJudger.work(), Coin2Silver.work(),
import os from flask import Flask, session, request from Auth import Auth import Helpers #MySQL server configuration mysql_config = Helpers.read_json_from_file("config/mysql_config.json") #Auth service auth_service = Helpers.service("auth") #Create an Auth instance auth = Auth(auth_service, mysql_config["host"], mysql_config["username"], mysql_config["password"], mysql_config["database"]) #Create a Flask app instance app = Flask(__name__) #Placeholders for HTML sign_up_html = "" sign_in_html = "" reset_password_html = "" #Get the HTML for the sign up page with open("signUp.html", 'r') as file: sign_up_html = file.read() #Get the HTML for the sign in page with open("signIn.html", 'r') as file: sign_in_html = file.read()
def __init__(self): self.authObject = Auth() self.credentials = self.authObject.authenticate()
from Auth import Auth from FacebookStrategy import FacebookStrategy from TwitterStrategy import TwitterStrategy from User import User # Auth with facebook user = User('user1') strategy = FacebookStrategy() token = Auth(strategy).auth(user) assert token == f'tokenFb{user.name}' # Auth with twitter user = User('user2') strategy = TwitterStrategy() token = Auth(strategy).auth(user) assert token == f'tokenTwitter{user.name}' print('All good')
# import the Flask class from the flask module from flask import Flask, render_template, redirect, url_for, request from Auth import Auth host = "localhost" username = "******" password = "******" database = "database" # create the application object app = Flask(__name__) sign_up = Auth("auth_server_name", host, username, password, database) # use decorators to link the function to a url @app.route('/') def home(): return render_template('home.html') # return a string @app.route('/signin', methods=['GET', 'POST']) def signin(): if request.method == 'POST': return redirect(url_for('home')) return render_template('signin.html') # render a template @app.route('/signup', methods=['GET', 'POST']) def signup(): return render_template('signup.html', methods=['GET', 'POST']) # render a template # if request.method == 'POST':
from fastapi import FastAPI from pydantic import BaseModel import uvicorn import requests import Auth.Auth as AuthModel import Util.Movies as MoviesModel app = FastAPI() Auth = AuthModel.Auth() Movies = MoviesModel.Movies() class LoginUser(BaseModel): email: str password: str class RegisterUser(BaseModel): email: str password: str phone: str address: str name: str class setUser(BaseModel): name: str age: int language: int math: int