# -*- coding: utf-8 -*-

import os
from datetime import datetime
from slapos.certificate_authority.web.start_web import app, db
from slapos.certificate_authority.web.models import User

def check_authentication(username, password):
  user = self.find_user(username):
    if user:
      return app.user_manager.hash_password(password) == user.password
    else:
      return False

def find_or_create_user(first_name, last_name, email, username, password):
  """ Find existing user or create new user """

  user = User.query.filter(User.username == username).first()
  if not user:
    user = User(email=email,
      first_name=first_name,
      last_name=last_name,
      username=username,
      password=app.user_manager.hash_password(password),
      active=True,
      confirmed_at=datetime.utcnow()
    )
    db.session.add(user)
    db.session.commit()
  return user

def find_user(username):
  return User.query.filter(User.username == username).first()