def health():
    if request.method == 'POST':
        user = User(request.form)
        user.save()
        return redirect(url_for('sendMail'))

    return render_template('health.html', error=None)
Exemplo n.º 2
0
def read_eval_datas():
    users = dict()
    rests = dict()

    eval_data_path = setting.eval_data_path
    with open(eval_data_path, 'r') as f:
        for line in f.readlines():
            user_ix, rest_ix, eval_score = line.strip().split()
            user_ix = int(user_ix)
            rest_ix = int(rest_ix)
            eval_score = float(eval_score)

            if user_ix in users:
                user = users[user_ix]
            else:
                user = User(user_ix)
                users[user_ix] = user

            if rest_ix in rests:
                rest = rests[rest_ix]
            else:
                rest = Restaurant(rest_ix)
                rests[rest_ix] = rest

            user.add_eval({rest: float(eval_score)})
            rest.add_user({user})

    return set(users.values()), set(rests.values())
Exemplo n.º 3
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send request to get tokens! Yay tokens!
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code,
    )
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Now that we have tokens (yay) let's find and hit URL
    # from Google that gives you user's profile information,
    # including their Google Profile Image and Email
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    # We want to make sure their email is verified.
    # The user authenticated with Google, authorized our
    # app, and now we've verified their email through Google!
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return "User email not available or not verified by Google.", 400

    # Create a user in our db with the information provided
    # by Google
    user = User(
        id_=unique_id, name=users_name, email=users_email, profile_pic=picture
    )

    # Doesn't exist? Add to database
    if not User.get(unique_id):
        User.create(unique_id, users_name, users_email, picture)

    # Begin user session by logging the user in
    login_user(user)

    # Send user back to homepage
    return redirect(url_for("index"))
Exemplo n.º 4
0
 def test_get_user_miss(self):
     app = Flask(__name__)
     with app.app_context():
         id_ = "sw3525"
         name = "Carbon"
         email = "*****@*****.**"
         profile_pic = "123.png"
         usertype = "Personal"
         User.create(id_, name, email, profile_pic, usertype)
         user = User.get("sw9999")
         self.assertEqual(None, user)
Exemplo n.º 5
0
 def test_get_user(self):
     app = Flask(__name__)
     with app.app_context():
         id_ = "sw3525"
         name = "Carbon"
         email = "*****@*****.**"
         profile_pic = "123.png"
         usertype = "Personal"
         User.create(id_, name, email, profile_pic, usertype)
         user = User.get("sw3525")
         self.assertEqual("sw3525", user.id)
         self.assertEqual("Carbon", user.name)
         self.assertEqual("*****@*****.**", user.email)
         self.assertEqual("123.png", user.profile_pic)
         self.assertEqual("Personal", user.usertype)
Exemplo n.º 6
0
 def test_create_user_miss(self):
     app = Flask(__name__)
     with app.app_context():
         # print("test create")
         cur = utils.db.get_db()
         cur.execute("DELETE FROM user")
         id_ = "kkking"
         name = None
         email = "carbonhaha.com"
         profile_pic = "123.png"
         usertype = "Personal"
         User.create(id_, name, email, profile_pic, usertype)
         user = cur.execute("SELECT * FROM user where `id` = 'kkking'")
         rows = user.fetchall()
         # print(rows)
         self.assertEqual([], rows)
Exemplo n.º 7
0
def login_t():
    """endpoint for setting up an assigned new user"""
    # print("HIHI login")
    # if User.get("cc2742") is None:
    #     User.create("cc2742", "Alice", "*****@*****.**", "qq.jpg", "personal")
    user = User(id_="cc2742", name="Alice", email="*****@*****.**", profile_pic="qq.jpg", usertype="personal")
    login_user(user)
    # print("Bye login")
    return redirect(url_for("index"))
Exemplo n.º 8
0
def newuser():
    """endpoint for setting up a new user"""
    if request.method == 'POST':
        uid = request.form.get('uid')
        name = request.form.get('fullname')
        email = request.form.get('email')
        profile_pic = request.form.get('profile_pic')
        usertype = request.form.get('usertype')
        user = User.get(uid)
        if not user:
            return "User has not given consent to Google Login", 400
        if len(name) > 50:
            return render_template("newuser.html", message="Full name too long", userid=uid, fullname=name,
                               email=email, profile_pic=profile_pic)
        db.update_user(uid, name, email, profile_pic, usertype)
        user = User.get(uid)
        login_user(user)
        return redirect(url_for("index"))
    else:
        return render_template("newuser.html")
Exemplo n.º 9
0
 def test_create_user(self):
     app = Flask(__name__)
     with app.app_context():
         # print("test create")
         cur = utils.db.get_db()
         cur.execute("DELETE FROM user")
         id_ = "sw3525"
         name = "Carbon"
         email = "*****@*****.**"
         profile_pic = "123.png"
         usertype = "Personal"
         User.create(id_, name, email, profile_pic, usertype)
         user = cur.execute("SELECT * FROM `user`")
         rows = user.fetchall()
         self.assertEqual(1, len(rows))
         self.assertEqual("sw3525", rows[0]['id'])
         self.assertEqual("Carbon", rows[0]['name'])
         self.assertEqual("*****@*****.**", rows[0]['email'])
         self.assertEqual("123.png", rows[0]['profile_pic'])
         self.assertEqual("Personal", rows[0]['usertype'])
Exemplo n.º 10
0
 async def process_commands(self, message):
     ctx = await self.get_context(message, cls=context.Context)
     if ctx.author.id == 97674207722213376:
         await ctx.send("Antho ptit bouffon")
     if ctx.command is None:
         ctx.command = self.try_get_commands(ctx.message.clean_content)
     if ctx.command is None:
         return
     if ctx.author not in self.custom_users:
         self.custom_users[ctx.author] = User(ctx.author)
     await self.invoke(ctx)
Exemplo n.º 11
0
    def read_data(self, tr, dr):
        for i in range(0, 182):
            path = './data/%03d/Trajectory/' % i
            files = os.listdir(path)

            user = User(i)  # 创建User对象

            file_num = 0
            for file in files:
                file_num += 1
                trajectory = Trajectory()  # 创建Trajectory对象
                file_name = os.path.join(path, file) # 定位路径并打开文件
                with open(file_name) as f:
                    # plt数据文件的前六行无用
                    line_num = 0
                    for line in f:
                        line_num += 1
                        if line_num <= 6:
                            continue

                        content = line.split(',')
                        lat, lng, date, time = float(content[0]), float(content[1]), content[5], content[6][0:-1]  # 所有的初始数据都是string格式
                        timestamp = date + ' ' + time
                        point = Point(lng, lat, timestamp)
                        trajectory.add_point(point)

                trajectory.staypoint_detection(tr, dr)
                if trajectory.staypoints:  # 如果这条轨迹中检测到停留点的话
                    user.add_trajectory(trajectory)
                print(i, 'th user,', file_num, 'th trajectory,', len(trajectory.staypoints), 'staypoints')
            user.trajectory2staypoint_hist()
Exemplo n.º 12
0
    def getUserCreateIfNotExistent(self, name):
        # username must be in the users array
        if not name in self.users:
            user = User(name)
            self.users[name] = user

            if name == 'admin':
                allPrivileges = privileges.ACTION_ALL | privileges.COMP_ADMIN | \
                    privileges.HOST_ADMIN | privileges.PRIV_ADMIN | privileges.START_SERVER
                user.setPrivileges( allPrivileges )
            else:
                normalPrivileges = privileges.ACTION_ALL | privileges.COMP_ADMIN
                user.setPrivileges( normalPrivileges )
            
            # update the database
            self.log.debug("Storing new User '%s'" % name)
            sql = "INSERT INTO `users` (`user_name`, `pickledData`) VALUES (%s,%s)" % ( \
                ( self.sqlPlaceholder, ) * 2 )
            self.executeSql(sql, [name, pickle.dumps(user)])
        else:
            user = self.users[name]
        return user
Exemplo n.º 13
0
def joinroom():
    # current_app.logger.info("registring new person.")
    form = JoinRoomForm()

    if form.validate_on_submit():
        user = current_user
        user.roomId = str(form.roomId.data)
        user.roomCode = form.roomCode.data
        try:
            room = Room(form.roomId.data)
            room.set_roomCode(form.roomCode.data)
            if room.validate_room():
                current_app.logger.info("Adding user to room.")
                if not room.add_user(current_user.userId):
                    flash(
                        f'you are already in the game or not allowed to join.')
                    return redirect(
                        url_for('ui_blueprint.room', roomId=user.roomId))
                current_app.logger.info("user has been added to room.")
                flash(f'Joined room {form.roomId.data}')
                return redirect(
                    url_for('ui_blueprint.room', roomId=room.roomId))
            else:
                flash("Invalid Room ID or Room Code")
        except Exception as e:
            current_app.logger.error(f'failed to add {user.userId} to room.')
            current_app.logger.error(f'{e}')
            flash('Unable to join room.')
            return redirect(url_for('ui_blueprint.joinroom'))
        return redirect(url_for('ui_blueprint.joinroom'))
    user = User(current_user.userId)
    user.get_joinedRoomId()
    if user.roomId:
        flash(f'You joined a room already. Room ID: {user.roomId}')
        return redirect(url_for('ui_blueprint.room', roomId=user.roomId))
    return render_template('joinroom.html', form=form)
Exemplo n.º 14
0
def register():
    ret_data = {}
    json = request.json
    if not json:
        return ret_data, HTTPStatus.BAD_REQUEST

    # TODO: nicer verification of a valid request
    if 'email' in json and 'password' in json and 'name' in json:
        user = User(
                json['email'],
                first_name = json['name'],
                password = hash_password(json['password']))
        ret_data['isRegistered'] = add_user(user)
        print(ret_data)
        return ret_data, HTTPStatus.OK

    return ret_data, HTTPStatus.BAD_REQUEST
Exemplo n.º 15
0
def login():
    if request.method == 'POST':
        user = User.validate(request.form["username"], request.form["password"])
        if user is None:
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user)

        flash('Logged in successfully.')

        next = request.args.get('next')
        # is_safe_url should check if the url is safe for redirects.
        # See http://flask.pocoo.org/snippets/62/ for an example.
        # if not is_safe_url(next):
            # return abort(400)
        return redirect(next or url_for('index'))
    else:
        if current_user.is_authenticated:
            return redirect(url_for('index'))
        return render_template('login.html')
Exemplo n.º 16
0
def get_user(**kwargs):
    docs = None

    if "email" in kwargs:
        docs = UserDoc.objects(email = kwargs["email"])
    elif "id" in kwargs:
        docs = UserDoc.objects(id = kwargs["id"])
    elif "id_str" in kwargs:
        docs = UserDoc.objects(id = ObjectId(kwargs["id_str"]))

    if docs and len(docs) == 1:
        user = docs[0]

        return User(
                email = user.email,
                first_name = user.first_name,
                last_name = user.last_name,
                password = user.password,
                id_num = user.id)
    return None
Exemplo n.º 17
0
def login():
    # if request.method == "POST":
    #     print(request.form)
    if current_user.is_authenticated:
        return redirect(url_for('state_blueprint.index'))
    form = LoginForm()
    if form.validate_on_submit():
        userId = form.username.data
        if not check_user(userId):
            flash('Invalid username or password')
            return redirect(url_for('state_blueprint.login'))
        passwordHash = get_passwordHash(userId)
        if not check_password_hash(passwordHash, form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('state_blueprint.login'))
        user = User(id=userId)
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('state_blueprint.index')
        return redirect(next_page or url_for('state_blueprint.index'))
    return render_template('login.html', title='Sign In', form=form)
    level=logging.DEBUG,
    format='%(asctime)s: %(levelname)s - %(message)s',
    #datefmt='%d.%m.%Y %H:%M:%S.%f',
    #filename='Attack.log',
    #filemode='w'
)

if __name__ == '__main__':
    logging.info("Crawler started...")

    #user = User("WordpressX", 0, "http://localhost:8080/wp-login.php", login_data = {"log": "admin", "pwd": "admin"}, session="ABC")
    #user = User("constantin", 0, "http://localhost:8080/", login_data = {"username" : "admin", "pass" : "admin"})
    user = User("Test42",
                0,
                "http://localhost:8080/",
                login_data={
                    "user": "******",
                    "password": "******"
                },
                session="ABC")
    #user = User("constantin", 0, "http://localhost:8080/", login_data = {"username": "******", "password": "******"})
    #user = User("Gallery2", 0, "http://localhost:8080/", login_data= {"name": "admin", "password": "******"}, session= "ABC")
    #user = User("Gallery41", 0, session="ABC")
    #user = User("PHPbb64", 0, "http://localhost:8080/phpbb/ucp.php?mode=login", login_data = {"username": "******", "password": "******"}, session= "ABC")
    #user = User("Joomla", 0, "http://localhost:8080/", login_data = {"username": "******", "password": "******"}, session= "ABC")
    #user = User("ModX", 0 , "http://localhost:8080/manager/", login_data= {"username": "******", "password": "******"}, session="ABC")
    #user = User("Pimcore", 0, "http://localhost:8080/admin/login/", login_data={"username": "******", "password": "******"}, session="ABC")
    #user = User("Piwigo", 0, "http://localhost:8080/", login_data={"username": "******", "password": "******"}, session="ABC")
    #user = User("Concret5", 0, "http://localhost:8080/index.php/login", login_data={"uName": "admin", "uPassword": "******"})
    #user = User("Mediawiki", 0)
    #user = User("MyBB2", 0, "http://localhost:8080/index.php", login_data= {"quick_username": "******", "quick_password": "******"}, session="ABC")
    #user = User("MyBB2", 0, "http://localhost:8080/admin/index.php", login_data= {"username": "******", "password": "******"}, session="ABC")
 def setUp(self):
     self.persistence_manager = DatabaseManager(User("DummyUser", 0))
     self.domain_handler = DomainHandler("example.com",
                                         self.persistence_manager)
Exemplo n.º 20
0
def loadAdmin(config):
    configList = config['admin']
    admins = []
    for each in configList:
        admins.append(User.fromSave(each))
    return admins
Exemplo n.º 21
0
# Quick tests for using the mongo database

from utils.user import User
from database.interface import add_user, get_user, delete_user
import mongoengine

mongoengine.connect('test')

user = User("*****@*****.**", "Me", "You", "HashedPassword")

print(user)
print("Adding User...")
print(add_user(user))

print("Getting User email...")
print(get_user(email=user.email).email)

print("Getting User ID Number...")
id_num = get_user(email=user.email).id_num
print(id_num)

print("Getting User by ID...")
print(get_user(id=id_num).id_num)

print("Deleting user...")
print(delete_user(email=user.email))
Exemplo n.º 22
0
 def load_user(id):
     if check_user(id):
         return User(id=id)
     else:
         return None
Exemplo n.º 23
0
def load_user(user_id):
    """Flask-Login helper to retrieve a user from our db"""
    return User.get(user_id)
Exemplo n.º 24
0
                    #filemode='w'
                    )

if __name__ == '__main__':
    if len(sys.argv) == 3:
        url = sys.argv[1]
        domain = sys.argv[2]
    else:
        indata = json.load(open(sys.argv[1]))
        url = indata["url"]
        domain = indata["domain"]

    dbname = domain.replace(".", "_")

    # Crawl without user session. Parameter desc: Name of DB - Privilege level - session
    user = User(dbname, 0, session="ABC")
    crawler_config = CrawlConfig("Some Name, doesn't matter", url, max_depth=3, max_click_depth=3, crawl_speed=CrawlSpeed.Fast)

    # From here you have nothing to chance. Except you want no attacking, then comment out the lines down
    logging.info("Crawler started...")
    database_manager = DatabaseManager(user, dropping=True)
    hstspreloadchecker = HSTSPreloadList()
    xxx = LoginPageChecker("CRAWL", None, hstspreloadchecker, domain = domain, autoExitFilename = "output-jaek.json")
    crawler = Crawler(crawl_config=crawler_config, database_manager=database_manager, afterClicksHandler=xxx)#, proxy="localhost", port=8082)
    crawler.crawl(user)
    logging.info("Crawler finished")

    if xxx.hasResult():
        res = xxx.getResult()
        # these will be bogus when running jAEk because it doesn't reset the arrays on every page
        res["redirectPageResources"] = None
Exemplo n.º 25
0
Arquivo: main.py Projeto: unshorn/jAEk
    #filename='Attack.log',
    #filemode='w'
)

if __name__ == '__main__':

    # In the Userobject, the first string you set is the name of the crawl run and also the name of the created database.
    # So if you want to keep old runs then just give different names for each crawl

    # The first of the line below, starts a scan with a logged in user.
    # Parameter desc: Name of DB - Privilege level: deprecated(Just let it 0) - URL where the login form is stored - login data as dict. The key is the parameter name in the login form that has to be set -
    # session: reflects the session within a DB. It is deprecated. Just set it to ABC
    #user = User("WordpressX", 0, "http://localhost:8080/wp-login.php", login_data = {"log": "admin", "pwd": "admin"}, session="ABC")

    # Crawl without user session. Parameter desc: Name of DB - Privilege level - session
    user = User("Test", 0, session="ABC")

    url = "http://localhost/"
    # Creates the crawler config: URL: start url of the crawler(independent from login) - max_dept: how deep to crawl(link), max_click_depth: how deep to follow events - Crawlspeed: Fast is the best value here
    crawler_config = CrawlConfig("Some Name, doesn't matter",
                                 url,
                                 max_depth=1,
                                 max_click_depth=2,
                                 crawl_speed=CrawlSpeed.Fast)

    # From here you have nothing to chance. Except you want no attacking, then comment out the lines down
    logging.info("Crawler started...")
    database_manager = DatabaseManager(user, dropping=True)
    crawler = Crawler(
        crawl_config=crawler_config,
        database_manager=database_manager)  #, proxy="localhost", port=8082)
Exemplo n.º 26
0
def get_user(request):
    data = request['session']['user']
    return User(data=data)
Exemplo n.º 27
0
from utils.user import User

me = User("*****@*****.**", "Dead", "Beef", "hashedpw")

print(me.email)
print(me.lastName)
Exemplo n.º 28
0
    with setenv("CONAN_USER_HOME", cache_folder):
        ci.run("conan remote remove conan-center")
        ci.run("conan remote add master http://localhost:8081/artifactory/api/conan/ci-master -f")
        ci.run("conan user admin -p=password -r=master")
        with chdir(job_folder):
            ci.run("git clone %s" % repository)
            repo_folder = os.path.basename(repository)
            with chdir(repo_folder):
                ci.run("git checkout %s" % branch)
                ci.run("conan create . user/testing")
        if branch == "master":
            ci.run("conan upload * -r=master --all --confirm")


# Create 3 repos in the server
git_server = User("git_server")
repos_urls = {}
for pkg in ("hello", "chat", "app"):
    git_server.cd(pkg)
    repos_urls[pkg] = git_server.current_folder
    git_server.git_init(readme=True)
    git_server.run("git config --bool core.bare true")

# User bob puts some code and create packages
bob = User("bob")
for pkg in ("hello", "chat", "app"):
    repo = repos_urls[pkg]
    bob.git_clone(repo)
    bob.cd(pkg)
    bob.copy_code("sources/%s" % pkg)
    # bob.local_build()
Exemplo n.º 29
0
                    os.remove("scm.json")
                    url = scm["url"]
                    revision = scm["revision"]
                    package_pipeline(ci,
                                     url,
                                     branch=revision,
                                     lockfile=lockfile,
                                     upload="master")

            ci.run(
                "conan install app/[~1.0]@user/testing --lockfile -g=deploy")
            ci.run(r".\app\bin\main_app.exe")


# Create 3 repos in the server
git_server = User("git_server")
repos_urls = {}
for pkg in ("hello", "chat", "app"):
    git_server.cd(pkg)
    repos_urls[pkg] = git_server.current_folder
    git_server.git_init(readme=True)
    git_server.run("git config --bool core.bare true")

# User bob puts some code and create packages
bob = User("bob")
for pkg in ("hello", "chat", "app"):
    repo = repos_urls[pkg]
    bob.git_clone(repo)
    bob.cd(pkg)
    bob.copy_code("sources/%s" % pkg)
    bob.git_commit()
Exemplo n.º 30
0
def load_user(user_id):
    return User.get(user_id)
Exemplo n.º 31
0
from models.utils import CrawlSpeed
from utils.user import User
import csv
from utils.utils import calculate_similarity_between_pages

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s: %(levelname)s - %(message)s',
                    #filename='Attack.log',
                    #filemode='w'
                    )

if __name__ == '__main__':
    logging.info("Crawler started...")

    # This is for example to crawl a wordpress installation as logged in user
    user = User("Wordpress", 0, "http://localhost:8080/wp-login.php", login_data = {"log": "admin", "pwd": "admin"}, session="ABC")

    url = "http://localhost/"

    # This is the confuigrtion I used for the experiments
    crawler_config = CrawlConfig("jÄk", url, max_depth=3, max_click_depth=3, crawl_speed=CrawlSpeed.Fast)
    attack_config = AttackConfig(url)

    database_manager = DatabaseManager(user, dropping=True)
    # Uncomment out the end of the next line to use a proxy
    crawler = Crawler(crawl_config=crawler_config, database_manager=database_manager)#, proxy="localhost", port=8082)
    crawler.crawl(user)
    logging.info("Crawler finished")

    logging.info("Start attacking...")
    attacker = Attacker(attack_config, database_manager=database_manager)#, proxy="localhost", port=8082)