Пример #1
0
def main():
    if platform.system() == 'Windows':
        os.system("title PoGoStick - Pokemon Go API")
        os.system("cls")
    elif platform.system() == 'Linux' or 'Darwin':
        sys.stdout.write("\x1b]2;PoGoStick - Pokemon Go API\x07")
        os.system("clear")
    else:
        os.system("clear")
        print("[!] Running on untested operating system.  Your mileage may vary.")

    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--auth", help="\"Google\" or \"PTC\" for authentication", required=True)
    parser.add_argument("-u", "--username", help="Username", default=None)
    parser.add_argument("-p", "--password", help="Password", default=None)
    args = parser.parse_args()
    if args.auth.lower() == "google":
        args.auth = "Google"
    elif args.auth.lower() == "ptc":
        args.auth = "PTC"
    else:
        print("[*] %s is not a valid authentication type.  Select Google or PTC." % args.auth)
        sys.exit(-1)

    if not args.username:
        args.username = raw_input("Username: ")
    if not args.password:
        args.password = getpass("Password: ")

    # Begin Flow
    auth.authenticate(args.username, args.password, args.auth)
    api.get_api_endpoint()
    actions.enumerate_profile()
Пример #2
0
def login():
    if request.method == 'POST':
        try:
            authenticate(request.form['username'], request.form['password'])
        except ValueError as e:
            return render_template('login.html', error=str(e))
        else:
            flash('You were logged in')
            return redirect(url_for('index'))
    else:
        if g.current_user:
            return redirect(url_for('index'))
        else:
            return render_template('login.html')
Пример #3
0
    def process_view(self, request, callback, callback_args, callback_kwargs):
        """
        Proces_view work before view rendering. Verify usere's ticket (from cookie or ticket attribute)
        """
        request.META['NEW_VPH_TKT_COOKIE'] = False

        try:
            #FROM COOKIE
            #Check user's cookie  if validate ticket is ok, update ticket timestamp else session expire.
            if request.session.get('vph-tkt'):
                try:
                    client_address = request.META['REMOTE_ADDR']
                    user, tkt64 = authenticate(ticket=request.session['vph-tkt'], cip=client_address)
                except:
                    logout(request)
                    request.META['VPH_TKT_COOKIE'] = True
                    request.ticket = None
                    return

                if user is None:
                    logout(request)
                    request.META['VPH_TKT_COOKIE'] = True
                    request.ticket = None
                    return
                request.ticket = tkt64
                request.META['VPH_TKT_COOKIE'] = tkt64

            else:

                if request.user.is_authenticated() and not request.user.username == 'admin':
                    logout(request)
                    request.ticket = None
                    request.META['VPH_TKT_COOKIE'] = True
                    return

            #FROM GET ATTRIBUTE
            #if validate ticket is ok, open new session and set ticket cookie only for super user , not avlid under api.

            if request.GET.get('ticket') and not request.path.count('api') and request.user.is_superuser:
                try:
                    ticket = binascii.a2b_base64(request.GET['ticket'])
                except :
                    return
                user, tkt64 = authenticate(ticket=request.GET['ticket'])
                if  user is not None :
                    login(request,user)
                    request.META['VPH_TKT_COOKIE'] = tkt64

        except KeyError:
            pass  # use default urlconf (settings.ROOT_URLCONF)
def main():
    # read configuration from file.
    read_config()
    
    # Execute app authentication. Must be set CLIENT_ID and CLIENT_SECRET into settings.ini.
    if OTHER_PORT:
        oauth, _, _ = authenticate(CLIENT_ID, CLIENT_SECRET, use_port=OTHER_PORT)
    else:
        oauth, _, _ = authenticate(CLIENT_ID, CLIENT_SECRET)

    # execute restore files.
    run_examples(oauth)
    printlog(app_consts.ENDED)
    
    os._exit(0)
Пример #5
0
 def send_file_to_client(self, username, password, path):
     if auth.authenticate(username, password):
         if auth.has_read(username, ROOTDIR + '/' + path):
             with open(ROOTDIR + path, "rb") as handle:
                 return xmlrpc.client.Binary(handle.read())
         else:
             return False
Пример #6
0
 def share_write(self, username, password, path, recipient):
     if auth.authenticate(username, password):
         abspath = ROOTDIR + '/' + path
         if auth.isOwner(username, abspath):
             auth.add_write(recipient, abspath)
             return True
         return False
def create_album(album_title):
    """create an album for registered user in imgur.com"""
    album_config = {
    'title': album_title,
    'description': 'images of menus {0}'.format(datetime.now())
    }
    # client = authenticate()
    # check if titled album already exist
    client = authenticate()
    albums = client.get_account_albums('me')
    print "albums:", albums
    no_album = True
    album_id = None
    for a in albums:
        print "album", a.id, a.title
        if a.title == album_title:
            album_id = a.id
            no_album = False
            print ("album already exist, id is %s" % album_id)
            return album_id # need to return id!!
    # print "album1", album #works
    if no_album:
        album=client.create_album(album_config)
        after_albums = client.get_account_albums('me')
        for a in after_albums:
            if a.title == album_title:
                album_id = a.id
                return album_id
Пример #8
0
def get_sio():
    ''' get information from SIO
    TODO: parse GWT response
    '''

    s = authenticate('https://s3.as.cmu.edu/sio/index.html')
    s.headers['Origin'] = 'https://s3.as.cmu.edu'
    s.headers['Referer'] = 'https://s3.as.cmu.edu/sio/index.html'
    s.headers['X-GWT-Module-Base'] = 'https://s3.as.cmu.edu/sio/sio/'
    s.headers['DNT'] = '1'
    s.headers['Content-Type'] = 'text/x-gwt-rpc; charset=UTF-8'

    siojs = s.get('https://s3.as.cmu.edu/sio/sio/sio.nocache.js').content
    permutation = re.search("Ub='([^']+)'", siojs).group(1)
    s.headers['X-GWT-Permutation'] = permutation

    page_name = 'https://s3.as.cmu.edu/sio/sio/%s.cache.html' % (permutation)
    cachehtml = s.get(page_name).content

    auth_key = re.search("vLi='([^']+)'", cachehtml).group(1)
    context_key = re.search("cHi='([^']+)'", cachehtml).group(1)
    content_key = re.search("BMi='([^']+)'", cachehtml).group(1)
    
    # info in user context: full name, major/school
    s.post('https://s3.as.cmu.edu/sio/sio/userContext.rpc', 
           data=('7|0|4|https://s3.as.cmu.edu/sio/sio/|%s|edu.cmu.s3.ui.common.client.serverproxy.user.UserContextService|initUserContext|1|2|3|4|0|' % context_key))

    s.post('https://s3.as.cmu.edu/sio/sio/authorization.rpc', 
                 data=('7|0|4|https://s3.as.cmu.edu/sio/sio/|%s|edu.cmu.s3.ui.sio.common.client.serverproxy.AuthorizationService|initLoggedInAsStudent|1|2|3|4|0|' % auth_key))

    s.post('https://s3.as.cmu.edu/sio/sio/bioinfo.rpc',
                 data=('7|0|4|https://s3.as.cmu.edu/sio/sio/|%s|edu.cmu.s3.ui.sio.student.client.serverproxy.bio.StudentBioService|fetchStudentSMCBoxInfo|1|2|3|4|0|' % content_key)).content
Пример #9
0
def login():
    error = None
    policy = re.compile('^\D{4,}\d{3}$')
    if request.method == 'POST':
        user = request.form['username'].lower()
        pwd = request.form['password']
        if policy.match(user) is None:
            return render_template('login.html', error=u'用户名格式错误')
        if not pwd:
            return render_template('login.html', error=u'密码不能为空')
        au_status = authenticate(user, pwd)
        if au_status == 'super':
            return redirect(url_for('backdoor'))
        elif au_status:
            ainfo = DB(user).search()
            if ainfo is None:
                session['otp_info'] = u'未绑定'
            else:
                if ainfo[4] is 1:
                    session['otp_info'] = u'已绑定'
                else:
                    session['otp_info'] = u'已禁用'
            session['user'] = user
            session['pwd'] = pwd
            session['logged_in'] = True
            return redirect(url_for('userinfo'))
        else:
            return render_template('login.html', error=u'用户名或密码错误')
    else:
        return render_template('login.html', error=error)
Пример #10
0
def upload():
    client = authenticate()
    urllist = upload_kitten(client)

    print urllist

    return urllist
Пример #11
0
def postSimpleMessage():

    postdata = request.body.read().decode("utf-8")

    message = "<Result><StatusCode>FAILED</StatusCode><Text>Authentication failed.</Text></Result>"

    tree = xmlParser.fromstring(postdata)

    userNameFromRequest, passwordFromRequest = auth.extractAuth(tree)

    if (auth.handleCommunityAuth(userNameFromRequest, passwordFromRequest)):

        message = "<Result><StatusCode>OK</StatusCode><Text></Text></Result>"
        handleAlerts(tree, True)

    elif auth.authenticate(userNameFromRequest, passwordFromRequest, mongohost, mongoport):

        message = "<Result><StatusCode>OK</StatusCode><Text></Text></Result>"
        handleAlerts(tree, False)
    else:
        print("Authentication failed....")

    response = {}
    headers = {'Content-type': 'application/html'}
    response['status'] = "Success"
    raise HTTPResponse(message, status=200, headers=headers)
Пример #12
0
def login(request, template='auth/userlogin.html', redirect_field_name=REDIRECT_FIELD_NAME):
    if request.GET.has_key('admin'):
        template = 'auth/adminlogin.html'

    if request.method == 'POST':
        redirect_to = request.REQUEST.get(redirect_field_name, '')
        loginname = request.POST.get('loginname', None)
        password = request.POST.get('password', None)

        user = authenticate(loginname = loginname, password = password)

        if user:

#            if user.is_alias():
#                __user = user
#                user = __user.alias_user
#                user.backend = __user.backend

            from auth import login
            login(request, user)

            if not redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

            if request.is_ajax():
                return render_to_response_json({"location": redirect_to, "errcode":0})

            return HttpResponseRedirect(redirect_to)

        if request.is_ajax():
            return render_to_response_json({"errcode":101})

    redirect_to =  request.META.get('HTTP_REFERER', "")
    return render_to_response(request, template, {redirect_field_name: redirect_to})
 def process_request(self, request):
     # AuthenticationMiddleware is required so that request.user exists.
     if not hasattr(request, 'user'):
         raise ImproperlyConfigured(
             "The Django remote user auth middleware requires the"
             " authentication middleware to be installed.  Edit your"
             " MIDDLEWARE_CLASSES setting to insert"
             " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
             " before the RemoteUserMiddleware class.")
     try:
         username = request.META[self.header]
     except KeyError:
         # If specified header doesn't exist then return (leaving
         # request.user set to AnonymousUser by the
         # AuthenticationMiddleware).
         return
     # If the user is already authenticated and that user is the user we are
     # getting passed in the headers, then the correct user is already
     # persisted in the session and we don't need to continue.
     if request.user.is_authenticated():
         if request.user.username == self.clean_username(username, request):
             return
     # We are seeing this user for the first time in this session, attempt
     # to authenticate the user.
     user = auth.authenticate(remote_user=username)
     if user:
         # User is valid.  Set request.user and persist user in the session
         # by logging the user in.
         request.user = user
         auth.login(request, user)
Пример #14
0
def login(error=None):
    if request.method=="GET":
        print 'ewargehstrdggrzhtfddf'
        print error
        err=''
        if error:
            err=auth.getError()
            if 'username' in session:
                session.pop('username',None)
        #if 'username' in session:
        #    return session['username'] +' is already logged in.'
        #else:
        
        return render_template('login.html', err=err)
    else:
        id_token=request.form['id']
        if auth.authenticate(id_token):
            user=auth.getName(id_token)
            session['username']=user
            #print session['username']
            #print 'authenticated'
            return render_template('index.html', user=session['username']), 200
        #msg=request.form['msg']
        #print msg
        #return redirect('/test')
        else:
            #print 'not logged in'
            error=auth.getError()
            print error
            return render_template('login.html'), 401 
Пример #15
0
    def RPC__User__login(self, username, password, remember=True):
        """Log in a user to the system using a username and password. """
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            self.return_api_error('username')
            return

        user = auth.authenticate(username=username, password=password)

        if self.config.auth and username == 'lab':
            user = None

        if user is None:
            self.return_api_error('password')
            return

        if not user.is_active:
            self.return_api_error('disabled')
            return

        if not remember:
            self.session.set_expiry(0)

        self.login(user)
        self.return_api_result()
Пример #16
0
def get_autolab_grades():
    #Autolab has their SSL certificates misconfigured, so we won't verify them
    s = authenticate('https://autolab.cs.cmu.edu/auth/users/auth/shibboleth',{"verify":False})

    main = s.get('https://autolab.cs.cmu.edu').content
    d = pq(main)
    current_courses = d('#content > .rolodex > .course > h1 > a')
    grades = {}

    for course in current_courses:
        page_1 = s.get('https://autolab.cs.cmu.edu%s/assessments' % d(course).attr('href')).content
        gradebook = pq(pq(page_1)('.action-links > li > a')[1]).attr('href')

        course_page = s.get('https://autolab.cs.cmu.edu%s' % gradebook).content
        course_name = d(course).text()
        cd = pq(course_page)

        grades[course_name] = {}

        assignments = cd('.grades tr')
        for assgn in assignments:
            if d(assgn).attr('class') == 'header': continue

            name = cd(assgn).find("td > span > a").text()
            score = cd(assgn).find("td > a").text()
            total = cd(assgn).find("span.max_score").text()

	    if name is not None and score is not None and total is not None:
	        grades[course_name][name] = [float(score), float(total)]


    return grades
Пример #17
0
def login(request):
    from auth import authenticate, login
    
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                next = request.POST.get('next', reverse("market_home"))
                return HttpResponseRedirect(next)
            else:
                request.flash['message'] = _("Your account is inactive... You must confirm your account before login.")
                request.flash['severity'] = "error"
        else:
            request.flash['message'] = _("You entered an invalid username or password. Please try again")
            request.flash['severity'] = "error"
            
        return render_to_response('%s/buy/login.html'% request.marketplace.template_prefix, 
                                  {'next': request.POST.get('next', None)},
                                  RequestContext(request))
    
    return render_to_response('%s/buy/login.html'% request.marketplace.template_prefix, 
                              {'next': request.GET.get('next', None)},
                              RequestContext(request))
Пример #18
0
def get_autolab_grades():
    s = authenticate('https://autolab.cs.cmu.edu')
    
    main = s.get('https://autolab.cs.cmu.edu').content
    d = pq(main)
    current_courses = d('#content > ul > li > a')
    grades = {}

    for course in current_courses:
        course_page = s.get('https://autolab.cs.cmu.edu%s/gradebook/student' % d(course).attr('href')).content
        course_name = d(course).text()
        cd = pq(course_page)

        grades[course_name] = {}

        assignments = cd('.grades tr')
        for assgn in assignments:
            if d(assgn).attr('class') == 'header': continue
            grade = d(assgn).text()
            matches = re.search('^([\D\s]*) \d ([\d\.]+) / ([\d\.]+)$', grade)

            if matches is not None:
                name = matches.group(1)
                score = float(matches.group(2))
                total = float(matches.group(3))

                grades[course_name][name] = [score, total]
                

    return grades
Пример #19
0
def get_sio():
    ''' get information from SIO
    TODO: figure out how to parse shit like the finances response
    '''

    s = authenticate('https://s3.as.cmu.edu/sio/index.html')
    s.headers['Content-Type'] = 'text/x-gwt-rpc; charset=UTF-8'

    siojs = s.get('https://s3.as.cmu.edu/sio/sio/sio.nocache.js').content
    permutation = re.search("Rb='([^']+)'", siojs).group(1)

    page_name = 'https://s3.as.cmu.edu/sio/sio/%s.cache.html' % (permutation)
    cachehtml = s.get(page_name).content

    # to successfully do RPC with SIO, you have to find the correct keys
    # for each different kind of RPC you're doing and send them with the request
    def get_key(key):
        var_name = re.search("'%s',(\w+)," % key, cachehtml).group(1)
        return re.search("%s='([^']+)'" % var_name, cachehtml).group(1)

    context_key = get_key('userContext.rpc')
    content_key = get_key('bioinfo.rpc')

    # GWT returns something that's _almost_ JSON but not quite
    def parse_gwt(gwt_response):
        return json.loads(gwt_response.replace("'", '"').replace("\\", "\\\\")[4:])

    return_data = {}

    # info in user context: full name, major/school
    s.post('https://s3.as.cmu.edu/sio/sio/userContext.rpc',
           data=('7|0|4|https://s3.as.cmu.edu/sio/sio/|%s|edu.cmu.s3.ui.common.client.serverproxy.user.UserContextService|initUserContext|1|2|3|4|0|' % context_key))

    # get mailbox/smc
    gwt_response =  s.post('https://s3.as.cmu.edu/sio/sio/bioinfo.rpc',
                           data=('7|0|4|https://s3.as.cmu.edu/sio/sio/|%s|edu.cmu.s3.ui.sio.student.client.serverproxy.bio.StudentBioService|fetchStudentSMCBoxInfo|1|2|3|4|0|' % content_key)).content
    sio_json = parse_gwt(gwt_response)

    return_data['smc'] = sio_json[5][2]
    return_data['mailbox_combo'] = sio_json[5][1]

    # get schedule
    now = datetime.now()
    currSemester = ('F' if now.month > 6 else 'S') + str(now.year % 100)
    cal = Calendar.from_string(s.get('https://s3.as.cmu.edu/sio/secure/export/schedule/%s_semester.ics?semester=%s' % (currSemester, currSemester)).content)
    day_map = {'MO': 1, 'TU': 2, 'WE': 3, 'TH': 4, 'FR': 5}
    return_data['schedule'] = []
    for event in cal.walk():
        if event.name != 'VEVENT': continue

        return_data['schedule'].append({
            'days': map(lambda day: day_map[day], event.get('rrule').get('byday')),
            'location': event.get('location').strip(),
            'summary': event.get('summary').strip(),
            'start_time': event.get('dtstart').dt,
            'end_time': event.get('dtend').dt
        })

    return return_data
Пример #20
0
    def RPC__User__authenticate(self, password):
        """Verify a password provided by the logged-in user. """
        user = auth.authenticate(username=self.user.username, password=password)

        if user is not None:
            self.return_api_result()
        else:
            self.return_api_error('invalid-password')
Пример #21
0
def auth(ws, data):
    user = authenticate(username=data['username'], password=data['password'])
    data = {
        'token': None
    }
    if user is not None:
        data['token'] = login(user)
    ws.send(json.dumps(data))
Пример #22
0
 def rm(self, username, password, filename):
     if auth.authenticate(username, password):
         print('authenticated')
         path = os.path.abspath(ROOTDIR + '/' + filename)
         if auth.isOwner(username, path):
             os.remove(path)
             return True
     return False
Пример #23
0
def login_url(request, loginname, ts, authcode, template = "auth/redirect.html"):
    user = authenticate(loginname = loginname, ts = ts, authcode = authcode)
    if user:
        from auth import login
        login(request, user)
        redirect = request.REQUEST.get(REDIRECT_FIELD_NAME, "")
        return render_to_response(request, template, {REDIRECT_FIELD_NAME: redirect})
    return HttpResponseForbidden
Пример #24
0
 def __init__(self, username, queue, apikey=None, token=None):
     self.endpoint = "https://iad.queues.api.rackspacecloud.com/"
     self.queue = queue
     self.username = username
     self.apikey = apikey
     if token : 
         self.token = token
     else:
         self.token = authenticate(username, apikey)
Пример #25
0
 def process_request(self, request):
     username = request.COOKIES.get(ERL_SESSION_KEY, None)
     token = request.COOKIES.get(ERL_SESSION_TOKEN, None)
     user = auth.authenticate(username=username, token=token) if username and token else None
     if user:
         request.user = user
         auth.login(request, user)
     else:
         request.user = auth.AnonymousUser()
Пример #26
0
def post_user():

    user = request.form.get('iUser', None)
    if (auth.authenticate(user, None)):
        session['innlogget'] = True
        session['user'] = user
        session['last_request'] = time.time()

    return redirect(url_for('input_url'))
Пример #27
0
 def POST(self):
     input = web.input()
     username = input.username
     password = input.password
     validate = authenticate(passwd=password,username=username)
     if validate:
         session.loggedin=1
         return "loggedin"
     else:
         return "username or password error"
Пример #28
0
def register():
    """Register a user."""
    if g.user:
        return redirect(url_for('index'))
    error = None
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif request.form['password'] != request.form['password2']:
            error = 'The two passwords do not match'
        elif get_user_id(request.form['username']) is not None:
            error = 'The username is already taken'
        else:
            user_create(request.form['username'], request.form['password'])
            authenticate(request.form['username'], request.form['password'])
            return redirect(url_for('settings'))
    return render_template('register.html', error=error)
Пример #29
0
    def get(self, request, format=None):
        # first authenticate and get access token if needed
        if self.access_token is None:
            self.access_token = auth.authenticate()

        # get the query and make the request
        query = request.query_params.get('q', '')
        r = dapi_make_request(query=query, access_token=self.access_token)

        return Response(r.json())
Пример #30
0
def post_login(request):
    username = request.params['login']
    password = request.params['password']
    came_from = request.params['came_from']
    if auth.authenticate(username, password, request):
        headers = remember(request, username)
        return HTTPFound(location = came_from,
                         headers = headers)
    else:
        request.invoke_subrequest(Request.blank('/login?came_from=' + came_from))