Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
 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)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
def daily_job():
    while (1):
        Auth.work()
        Capsule.work()
        Coin2Silver.work()
        GiftSend.work()
        Group.work()
        Heart.work()
        Silver2Coin.work()
        SilverBox.work()
        Task.work()
        # 休息0.5s,减少CPU占用
        time.sleep(0.5)
Ejemplo n.º 7
0
    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
Ejemplo n.º 8
0
 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")
     ]
Ejemplo n.º 9
0
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']))
Ejemplo n.º 10
0
async def main():

    daily_tasks = [
        CaseJudger.work(),
        Coin2Silver.work(),
        GiftSend.work(),
        Group.work(),
        Silver2Coin.work(),
        Task.work(),
        MainDailyTask.work(),
        MatchTask.work()
    ]

    # 先登陆一次
    Auth.work()

    for task in daily_tasks:
        await task
Ejemplo n.º 11
0
class App:
    def __init__(self):
        self.authObject = Auth()
        self.credentials = self.authObject.authenticate()

    def deleteCredentials(self):
        if not (self.authObject.SAVE_CREDENTIALS):
            if (os.path.exists('data/secrets.json')):
                os.remove('data/secrets.json')
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)
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
    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()
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
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():
Ejemplo n.º 18
0
 def get(self):
     return Auth.logout()
Ejemplo n.º 19
0
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(),
Ejemplo n.º 20
0
                #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
Ejemplo n.º 21
0
 def set_auth(self, login, password = '******'):
     self.auth = Auth(login, password)
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
from Task import Task
from Sentence import Sentence
from Timer import Timer
from Config import *
from configcheck import ConfigCheck
from optparse import OptionParser
from API import API
from Monitor_Server import MonitorServer
from Version import version
from CaseJudger import CaseJudger
from MainDailyTask import MainDailyTask
from MatchTask import MatchTask

# 初始化所有class
API = API()
Auth = Auth()
Capsule = Capsule()
CaseJudger = CaseJudger()
Coin2Silver = Coin2Silver()
DailyBag = DailyBag()
GiftSend = GiftSend()
Group = Group()
Heart = Heart()
Silver2Coin = Silver2Coin()
SilverBox = SilverBox()
Task = Task()
rafflehandler = RaffleHandler()
MainDailyTask = MainDailyTask()
MatchTask = MatchTask()
MonitorServer = MonitorServer(config["Server"]["ADDRESS"], config["Server"]["PASSWORD"])
Ejemplo n.º 24
0
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)
Ejemplo n.º 25
0
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()
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')
Ejemplo n.º 27
0
import xbmc, xbmcgui, xbmcplugin, xbmcaddon

Addon = xbmcaddon.Addon(id='plugin.video.fepcom.net')
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

Ejemplo n.º 28
0
 def post(self):
     return Auth.login()
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
 def __init__(self):
     self.authObject = Auth()
     self.credentials = self.authObject.authenticate()
Ejemplo n.º 31
0
Archivo: default.py Proyecto: serbra/ru
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
Ejemplo n.º 32
0
# 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':
Ejemplo n.º 33
0
class Ssh(QtCore.QObject):
    """
    Class created by PyUML

    
    # PyUML: Do not remove this line! # XMI_ID:_sfuNQBCnEd-9mr2Tj73dvA

    # PyUML: Associations of this class:
    # PyUML: Association (being 'src') to class ServersPool (being 'dst') in package /base/ 
    # PyUML: Association (being 'dst') to class Server (being 'src') in package /base/ 
    # PyUML: Association (being 'dst') to class Auth (being 'src') in package /base/ 
    # PyUML: Association (being 'src') to class Monitor (being 'dst') in package /base/ 
"""
    server = None  # created by PyUML

    def __init__(self, host, port, type, id = 0):
        super(Ssh, self).__init__()
        
        self.auth = None  # created by PyUML
        self.server = Server(host, port, type, id)
        
        self.client = paramiko.SSHClient()
        self.client.load_system_host_keys()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.isConnected = False
        
        self.monitoring = Monitor(self)
    
    def __del__(self):
        self.close()
        
    def set_auth(self, login, password = '******'):
        self.auth = Auth(login, password)
    
    def connect_thread(self):
        try:
            if self.auth.is_rsa():
                self.client.connect(self.server.host, self.server.port, self.auth.login, key_filename=self.auth.get_rsa_files(), timeout=25)
            else:
                self.client.connect(self.server.host, self.server.port, self.auth.login, self.auth.password, timeout=25)
            self.isConnected = self.client.get_transport().is_active()
            
            if(self.isConnected):
                self.client.get_transport().set_keepalive(300)
            
            hostname, os = self.sendCommand('hostname && uname').split()
            self.server.set_hostname(hostname)
            self.server.set_os(os.lower())
            
            # Emits signal that server is connected
            self.emit(QtCore.SIGNAL('connected'), self)
            
            return True
        
        except:
            # Emits signal that server is connected
            self.emit_notconnected()
            #self.emit(QtCore.SIGNAL('notConnected'), self)
            
            print 'Unable to connect to %s:%s with login %s, pass %s' % (self.server.host, self.server.port, self.auth.login, self.auth.password)
            QtCore.QCoreApplication.processEvents();
            
            try:
                self.client.close()
            except:
                pass
            return False

    def connect(self):
        try:
            self.close()
        finally:
            # Connect to the servers (thread-safe)
            # Random avoid to fail a connection on windows when all connections
            # are initialized
            global connectDelay
            t = Timer(connectDelay, self.connect_thread)
            t.start()
            connectDelay += .1

    def close(self):
        self.client.close()
        if self.isConnected:
            # Emits signal that server is connected
            self.emit_notconnected()
        self.isConnected = False
        #self.emit(QtCore.SIGNAL('notConnected'), self)

    def sendCommand(self, command):
        if self.isConnected:
            if not self.client.get_transport().is_active():
                self.isConnected = False
                # Emits signal that server is connected
                self.emit_notconnected()
                #self.emit(QtCore.SIGNAL('notConnected'), self)
            
            stdin, stdout, stderr = self.client.exec_command(command)
            response = stdout.read()
            
            if response == False:
                return stderr.read()
            else:
                return response
        else:
            return False
    
    def sendInteractiveCommand(self, command, args):
        if self.isConnected:
            i = 0
            stdin, stdout, stderr = self.client.exec_command(command)
            while stdout.channel.closed is False:
                stdin.write('%s\n' % args[i])
                stdin.flush()
                ++i
            # Reinitialize sudo
            self.sendCommand('sudo -k')
            response = stdout.read()
            
            if response == False:
                return stderr.read()
            else:
                return response
        else:
            return False
    
    def monitor(self, interval = 5.0):
        self.monitoring.set_interval(interval)
        self.monitoring.start()
    
    def open_interactive_shell(self):
        if platform.system() == 'Linux':
            try:
                # Gnome
                subprocess.Popen('gnome-terminal -e "ssh ' + self.server.host + ' -p ' + str(self.server.port) + ' -l ' + str(self.auth.login) + '"', shell=True)
                
            except:
                # KDE
                try:
                    subprocess.Popen('konsole -e "ssh ' + self.server.host + ' -p ' + str(self.server.port) + ' -l ' + str(self.auth.login) + '"', shell=True)
                except:
                    print 'No terminal found'
            
        elif platform.system() == 'Darwin':
            subprocess.Popen('/bin/sh base/term.sh /usr/bin/ssh ' + self.server.host + ' -p ' + str(self.server.port) + ' -l ' + str(self.auth.login), shell=True)
            #try:
            #    # Mac OSX
            #    subprocess.Popen('open -n -a /Applications/Utilities/Terminal.app /usr/bin/ssh ' + self.server.host + ' -p ' + str(self.server.port) + ' -l ' + str(self.auth.login), shell=True)
            #except:
            #    print 'No terminal found'
            
        elif platform.system() == 'Windows':
            # Windows
            try:
                subprocess.Popen('putty.exe -ssh -2 -P ' + str(self.server.port) + ' ' + str(self.auth.login) + '@' + self.server.host + ' -pw ' + str(self.auth.password), shell=True)
            except:
                print 'No terminal found'
    
    def emit_notconnected(self):
        self.emit(QtCore.SIGNAL('notConnected'), self)