Skip to content

Commit

Permalink
BREAK - Change database column
Browse files Browse the repository at this point in the history
  • Loading branch information
Loïc PORTE committed Mar 2, 2015
1 parent 64a7be1 commit 2763eb9
Show file tree
Hide file tree
Showing 13 changed files with 85 additions and 68 deletions.
5 changes: 4 additions & 1 deletion Demo/auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ class DemoAuth:
def __init__(self, config):
raise NotImplementedError

# Must return email if ok or False
# Must return login if ok or False
def check_auth(self, user, password):
raise NotImplementedError

def is_admin(self, user):
return False
16 changes: 13 additions & 3 deletions Demo/auth/auth_fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,19 @@
class AuthFake(DemoAuth):
def __init__(self, config):
self.config = config
users = self.config['user'].split(',')
self.users = {}
for users_info in users:
user_info = users_info.split(':')
self.users[user_info[0]] = user_info[1]

def check_auth(self, user, password):
if user in self.config:
if password == self.config[user]:
return user + '@fake.com'
if user in self.users:
if password == self.users[user]:
return user
return False

def is_admin(self, user):
if user in self.config['admin'].split(','):
return True
return False
15 changes: 3 additions & 12 deletions Demo/auth/auth_ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ def __init__(self, config):
self.bind_password = config['bind_password']
self.search_base = config['search_base']
self.login_attribute = config['login_attribute']
self.email_attribute = config['email_attribute']

def check_auth(self, user, password):
try:
Expand All @@ -26,23 +25,15 @@ def check_auth(self, user, password):
except ldap.INVALID_CREDENTIALS as e:
return False

if (len(res) > 1):
if len(res) > 1:
raise Exception("To much user returned")
if (len(res) < 1):
if len(res) < 1:
raise ldap.INVALID_CREDENTIALS

dn, attributes = res[0]
if not self.try_bind(dn, password):
return False
return self.get_email(dn)

def get_email(self, dn):
ld = ldap.initialize(self.host)
ld.simple_bind_s(self.bind_user, self.bind_password)
res = ld.search_s(dn, ldap.SCOPE_BASE)
dn, attributes = res[0]
ld.unbind_s()
return attributes[self.email_attribute][0]
return user

def try_bind(self, dn, password):
ld = ldap.initialize(self.host)
Expand Down
4 changes: 2 additions & 2 deletions Demo/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_session(config):
class Instance(Base):
__tablename__ = 'instance'
id = Column(types.Integer, primary_key=True)
openstack_id = Column(String(255), unique=True)
provider_id = Column(String(255), unique=True)
name = Column(String(255))
image_key = Column(String(255))
status = Column(String(255), nullable=False)
Expand All @@ -45,7 +45,7 @@ class Instance(Base):
class User(Base):
__tablename__ = 'user'
token = Column(String(255), primary_key=True)
email = Column(String(255), unique=True)
login = Column(String(255), unique=True)
last_connection = Column(types.DATETIME)

def generate_token(self):
Expand Down
37 changes: 13 additions & 24 deletions Demo/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import datetime
from demo_exception import *
from demo_mail import DemoMail
import re
import os


Expand Down Expand Up @@ -67,7 +66,7 @@ def get_class_name(mod_name):

def get_type(self, instance_id):
query = self.database.query(Instance).filter(
Instance.openstack_id == instance_id
Instance.provider_id == instance_id
)
data_instance = query.first()
return data_instance.image_key
Expand All @@ -79,7 +78,7 @@ def get_soft_address(self, instance):

def get_life_time(self, id):
query = self.database.query(Instance).filter(
Instance.openstack_id == id
Instance.provider_id == id
)
data_instance = query.first()
delta = (
Expand All @@ -92,7 +91,7 @@ def get_life_time(self, id):

def get_ask_time(self, id):
query = self.database.query(Instance).filter(
Instance.openstack_id == id
Instance.provider_id == id
)
data_instance = query.first()
return data_instance.life_time
Expand Down Expand Up @@ -168,7 +167,7 @@ def database_insert_server(self, instance_id, status=None,
logging.debug('Insert instance %s', instance_id)

query = self.database.query(Instance).filter(
Instance.openstack_id == instance_id
Instance.provider_id == instance_id
)

if query.count() > 0:
Expand All @@ -177,7 +176,7 @@ def database_insert_server(self, instance_id, status=None,
data_instance = Instance()
data_instance.launched_at = datetime.datetime.now()

data_instance.openstack_id = instance_id
data_instance.provider_id = instance_id
data_instance.status = status

if image_key:
Expand All @@ -204,7 +203,7 @@ def database_remove_server(self, id):

# database
query = self.database.query(Instance).filter(
Instance.openstack_id == id
Instance.provider_id == id
)
database_instance = query.first()
database_instance.status = 'DELETED'
Expand All @@ -222,7 +221,7 @@ def database_count_active_instance(self, image_key):
def instance_add_time(self, instance_id, add_time):

query = self.database.query(Instance).filter(
Instance.openstack_id == instance_id
Instance.provider_id == instance_id
)
data_instance = query.first()

Expand All @@ -242,21 +241,17 @@ def instance_add_time(self, instance_id, add_time):
# END DATABASE #

# USER #
def create_user(self, email=None):
def create_user(self, login=None):
user = User()
if email is not None:
# Email is valid
if not self.check_email(email):
raise DemoExceptionInvalidEmail(email)

if login is not None:
# User already exist ?
query = self.database.query(User).filter(
User.email == email
User.login == login
)
if query.count() >= 1:
return query.first()

user.email = email
user.login = login
user.generate_token()
user.last_connection = datetime.datetime.now()

Expand Down Expand Up @@ -284,9 +279,9 @@ def get_user_by_token(self, token):
return user

def check_user_own_instance(self, token,
openstack_id, raise_exception=True):
provider_id, raise_exception=True):
query = self.database.query(Instance).filter(
Instance.openstack_id == openstack_id
Instance.provider_id == provider_id
)
instance = query.first()
if instance is not None and instance.token == token:
Expand Down Expand Up @@ -319,12 +314,6 @@ def placeholder_apply(self, param, instance_id):
param = param.replace("%ip%", ip)
return param

def check_email(self, email):
pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
if re.match(pattern, email):
return True
return False

# Python 2.6 hook
def _get_total_seconds(self, td):
return (
Expand Down
24 changes: 19 additions & 5 deletions Demo/demo_mail.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# coding=utf-8
# -*- coding: utf-8 -*-
import smtplib
import logging
import re
from demo_exception import DemoExceptionInvalidEmail


class DemoMail():
Expand All @@ -27,6 +29,10 @@ def connect(self):

def send_token_mail(self, mail, token, url):
logging.debug('Send token mail to %s with token %s', mail, token)
# Email is valid
if not DemoMail.check_email(mail):
raise DemoExceptionInvalidEmail(mail)

header = str('To:' + mail + '\n' +
'From: ' + self.from_mail + '\n' +
'Subject:testing \n')
Expand All @@ -37,7 +43,15 @@ def send_token_mail(self, mail, token, url):
smtp_server.close()

def get_token_mail_body(self, token, url):
return "Bonjour\n" \
"Voici le lien qui vous permettra" +\
"d'accéder à vos instances de démonstrations\n" \
+ url + "#/login/" + token
body = "Bonjour\n" \
"Voici le lien qui vous permettra"\
"d'accéder à vos instances de démonstrations\n"\
+ url + "#/login/" + token.encode("utf-8")
return body

@staticmethod
def check_email(email):
pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
if re.match(pattern, email):
return True
return False
12 changes: 6 additions & 6 deletions Demo/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def instance_info(self, instance_id):
def get_user(self):
info = {
'token': self.user.token,
'email': self.user.email
'login': self.user.login,
}
self.headers_to_send['Content-type'] = 'application/json'
self.send_all_header(200)
Expand All @@ -109,7 +109,7 @@ def user_instances_info(self):
info = []
for instance in instances:
info.append({
'id': instance.openstack_id,
'id': instance.provider_id,
'status': instance.status,
'type': instance.image_key,
'launched_at': str(instance.launched_at),
Expand Down Expand Up @@ -261,7 +261,7 @@ def do_PUT(self):
url = 'http://'+self.headers.getheader('Host')+'/'
email = put_vars['email']
user = self.demo.create_user(email)
self.demo.mail.send_token_mail(user.email, user.token, url)
self.demo.mail.send_token_mail(user.login, user.token, url)
self.send_all_header()
return
else:
Expand Down Expand Up @@ -350,12 +350,12 @@ def do_DELETE(self):

match = re.match("/api/instance/(.*)", self.path)
if match:
openstack_id = match.group(1)
provider_id = match.group(1)
self.demo.check_user_own_instance(
self.user.token,
openstack_id
provider_id
)
self.demo.database_remove_server(openstack_id)
self.demo.database_remove_server(provider_id)
self.send_http_message(200, 'ok')
return
self.send_http_error(404, 'No action')
Expand Down
14 changes: 8 additions & 6 deletions Demo/vacuum.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,30 +31,32 @@ def check_old_instance(self):
)
logging.debug(
'%s must be destroy at %s',
data_instance.openstack_id, destroy_at
data_instance.provider_id, destroy_at
)
if destroy_at < datetime.datetime.now():
logging.info('%s is to old', data_instance.openstack_id)
demo.database_remove_server(data_instance.openstack_id)
logging.info('%s is to old', data_instance.provider_id)
demo.database_remove_server(data_instance.provider_id)

on_cloud = False
for id in instances:
if data_instance.openstack_id == id:
if data_instance.provider_id == id:
on_cloud = True
break
if not on_cloud and data_instance.openstack_id:
if not on_cloud and data_instance.provider_id:
logging.info(
'%s is not present on cloud anymore',
data_instance.id
)
demo.database_remove_server(data_instance.openstack_id)
demo.database_remove_server(data_instance.provider_id)

def run(self):
time_between_vacuum = 60
while True:
try:
self.check_old_instance()
except Exception as e:
if self.config.dev:
raise
logging.error("Vaccum Raise Execption %s", e.message)
i = 0
while i < time_between_vacuum:
Expand Down
2 changes: 1 addition & 1 deletion test/functional/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ def test_get_info(self):
rep = self.rep_to_dict(r.text)

self.assertEqual(200, r.status_code)
self.assertEqual('admin@fake.com', rep['email'])
self.assertEqual('admin', rep['login'])
3 changes: 2 additions & 1 deletion test/samples/config/config-fake.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
log_level=DEBUG
security_type=auth_fake
provider=fake
dev=true

[AUTH_FAKE]
user:admin:admin,test:test
admin:admin
test:test

[HTTP]
port=8080
Expand Down
4 changes: 2 additions & 2 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
<li>
<a href="#list"><i class="fa fa-list-alt"></i>{{ 'LIST_INSTANCE'|translate }}</a>
</li>
<li ng-show="user.email">
<a href="#" ng-click="disconnect()"><i class="fa fa-sign-out"></i>{{ user.email }} </a>
<li ng-show="user.login">
<a href="#" ng-click="disconnect()"><i class="fa fa-sign-out"></i>{{ user.login }} </a>
</li>
</ul>
</div>
Expand Down
4 changes: 2 additions & 2 deletions web/js/controller/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ demoApp.controller('loginMailController', function($scope, $http) {
console.log(error)
};

$scope.user = { 'email': '' };
$scope.user = { 'login': '' };

$scope.addUser = function () {
$http.put('/api/user',$scope.user).
Expand All @@ -22,7 +22,7 @@ demoApp.controller('loginAuthController', function($scope, $http, $location, $ro
console.log(error)
};

$scope.user = { 'user': '', 'password':'' };
$scope.user = { 'login': '', 'password':'' };

$scope.connect = function () {
$http.post('/api/connect',$scope.user).
Expand Down
Loading

0 comments on commit 2763eb9

Please sign in to comment.