Skip to content

Commit

Permalink
Merge pull request #18 from GeographicaGS/dev_raul_managing
Browse files Browse the repository at this point in the history
Dev raul managing
  • Loading branch information
neokore authored Jun 20, 2016
2 parents 1ac232e + 71aece2 commit f104a89
Show file tree
Hide file tree
Showing 133 changed files with 6,476 additions and 575 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ venv/
api/model/base/PostgreSQL/config.py
tempimages/
images/
www/cdn/tmp/
www/src/node_modules/
Empty file modified api/.gitignore
100755 → 100644
Empty file.
22 changes: 22 additions & 0 deletions api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
## API usage

- Create virtual environment:
```
$ pip install virtualenv
$ cd projectname/api
$ virtualenv venv
$ . venv/bin/activate
$ pip install requirements.txt
$ deactivate
```

- Run API:
```
$ . venv/bin/activate
$ python run.py
```

- Exit from virtual environment:
```
$ deactivate
```
7 changes: 5 additions & 2 deletions api/api/__init__.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from flask import Flask, jsonify

app = Flask(__name__)
import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')

app = Flask(__name__, template_folder=tmpl_dir)

import config
import trans
import home
import proxy

@app.route('/', methods = ['GET'])
@app.route('/', methods = ['GET'])
def alive():
return jsonify( { "status" : "running"})
106 changes: 90 additions & 16 deletions api/api/authutil.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# coding=UTF8

from api import app
from flask import request,abort
from flask import request, abort, render_template
from model.usermodel import UserModel
import md5
import datetime
Expand All @@ -26,7 +26,7 @@ def decorator(*args, **kwargs): #1
m = md5.new()
m.update(suma)
hashsum = m.hexdigest()

if(hashsum != request.headers['hash']):
abort(401)
else:
Expand All @@ -38,44 +38,118 @@ def decorator(*args, **kwargs): #1
return func(*args, **kwargs)
return decorator

def authAdmin(func):
@wraps(func)
def decorator(*args, **kwargs): #1
if (request.headers['hash'] is not None and request.headers['timestamp'] is not None and request.headers['username'] is not None):
# Control timestamp
usertimestamp = datetime.datetime.fromtimestamp(int(request.headers['timestamp'])/1000)
maxtime = usertimestamp + datetime.timedelta(minutes=app.config["loginMaxTime"])
diftime = datetime.datetime.now() - maxtime
if (diftime <= datetime.timedelta(seconds=0)):

# Control credentials
usermodel = UserModel()
user = usermodel.getUserByUsername(request.headers['username'])
if user is not None and user['admin']:
password = usermodel.getPasswordByUsername(request.headers['username'])

if(password != ''):
suma = request.headers['username'] + password + request.headers['timestamp']
m = md5.new()
m.update(suma)
hashsum = m.hexdigest()

if(hashsum != request.headers['hash']):
abort(401)
else:
abort(401)
else:
abort(401)
else:
abort(401)
else:
abort(401)
return func(*args, **kwargs)
return decorator

def sendEmail(toAddresses,subject,body):
# Import smtplib for the actual sending function
import smtplib

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.header import Header

server = smtplib.SMTP(host=app.config["smtpServer"], port=app.config["smtpPort"], timeout=10)

if app.config["smtpTLS"]:
if app.config["smtpTLS"]:
server.starttls()

server.ehlo()

if app.config["smtpAuth"]:
if app.config["smtpAuth"]:
server.login(app.config["smtpUser"], app.config["smtpPassword"])

fromAddr = app.config["smtpFromAddr"]

msg = MIMEMultipart('alternative')
msg['From'] = '"%s"<%s>' % (app.config["smtpFromAddrName"], app.config["smtpFromAddr"])
msg['To'] = ",".join(toAddresses)
msg['Subject'] = Header(subject,'utf-8')

msg.attach(MIMEText(body.encode("utf-8"), 'html','utf-8'))

text = msg.as_string()

try:
server.sendmail(fromAddr, toAddresses, text)
finally:
server.quit()

def getConfirmationEmailBody(user,code,lang="es"):
link = "<a href='"+ app.config["baseURL"] +"/" + lang + "/user/" + user + "/" + code + "' target='_blank'>"+app.trans['EMAIL_MSG_LINK'][lang]+"</a>"
m = "<h2>"+app.trans['EMAIL_TITLE'][lang]+"</h2>"
m += "<h2>"+app.trans['EMAIL_MSG_CONFIRM'][lang]+"</h2>"
m += "<p>" + app.trans['EMAIL_MSG_PRELINK'][lang] + link + app.trans['EMAIL_MSG_POSTLINK'][lang] +"</p>"
def sendAccountConfirmationEmail(username, userrealname, code, email, lang="es"):
link = app.config["baseURL"] +"/" + lang + "/user/" + username + "/" + code
body = render_template('email_accountconfirmation_%s.html' % lang, confirmationurl=link, userrealname=userrealname)
sendEmail([email], app.trans['EMAIL_ACCOUNTCONFIRMATION_SUBJECT'][lang], body);

def sendNewHistoryNotification(user, history):
history['url'] = app.config["baseURL"] + "/" + user['lang'] + "/join/history/" + str(history['id_history'])
if user['admin']:
body = render_template('email_newhistory_admin_%s.html' % (user['lang']), history=history)
else:
body = render_template('email_newhistory_author_%s.html' % (user['lang']), history=history)
sendEmail([user['email']], app.trans['EMAIL_NEWHISTORY_SUBJECT'][user['lang']], body);

def sendEditedHistoryNotification(user, history):
history['url'] = app.config["baseURL"] + "/" + user['lang'] + "/join/history/" + str(history['id_history'])
if user['admin']:
body = render_template('email_editedhistory_admin_%s.html' % (user['lang']), history=history)
else:
body = render_template('email_editedhistory_author_%s.html' % (user['lang']), history=history)
sendEmail([user['email']], app.trans['EMAIL_EDITEDHISTORY_SUBJECT'][user['lang']], body);

def sendPublishedHistoryNotification(user, history):
history['url'] = app.config["baseURL"] + "/" + user['lang'] + "/join/history/" + str(history['id_history'])
if user['admin']:
if history['status'] == 1:
subject = app.trans['EMAIL_PUBLISHEDHISTORY_SUBJECT'][user['lang']]
body = render_template('email_publishedhistory_admin_%s.html' % (user['lang']), history=history)
else:
subject = app.trans['EMAIL_UNPUBLISHEDHISTORY_SUBJECT'][user['lang']]
body = render_template('email_unpublishedhistory_admin_%s.html' % (user['lang']), history=history)
else:
if history['status'] == 1:
subject = app.trans['EMAIL_PUBLISHEDHISTORY_SUBJECT'][user['lang']]
body = render_template('email_publishedhistory_author_%s.html' % (user['lang']), history=history)
else:
subject = app.trans['EMAIL_UNPUBLISHEDHISTORY_SUBJECT'][user['lang']]
body = render_template('email_unpublishedhistory_author_%s.html' % (user['lang']), history=history)
sendEmail([user['email']], subject, body);

return m;
def sendDeletedHistoryNotification(user, history):
history['url'] = app.config["baseURL"] + "/" + user['lang'] + "/join/history/" + str(history['id_history'])
if user['admin']:
body = render_template('email_deletedhistory_admin_%s.html' % (user['lang']), history=history)
else:
body = render_template('email_deletedhistory_author_%s.html' % (user['lang']), history=history)
sendEmail([user['email']], app.trans['EMAIL_DELETEDHISTORY_SUBJECT'][user['lang']], body);
48 changes: 29 additions & 19 deletions api/api/config_changes.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,34 @@
cdnPath = baseRootPath + "/www/cdn"

app.config.update(
DEBUG=False,
SECRET_KEY="XXXX",
baseURL = "",
smtpServer="localhost",
smtpPort=25,
smtpUser="",
smtpPassword="",
smtpFromAddr="",
smtpFromAddrName="DEV alboran",
smtpTLS = False,
smtpAuth = False,
convertBin = "convert",
UPLOAD_TEMP_FOLDER= baseRootPath +"/tempimages/",
IMAGES_FOLDER= cdnPath +"/images/",
ALLOWED_EXTENSIONS=set(["jpg","jpeg","png"]),
baseURL='http://xxxxxxxxxxx',
DEBUG=True,
SECRET_KEY='xxxxxxxxxx',
smtpServer='xxxxxxxxxxx',
smtpPort=587,
smtpUser='xxxxxxxxxxxxx',
smtpPassword='xxxxxxxxxxxxxxxxxxxx',
smtpTLS=True,
smtpAuth=True,
smtpFromAddr='xxxxxxxxxxxxxxxxxxxxxxxxxx',
smtpFromAddrName='Geoportal Alboran',
UPLOAD_TEMP_FOLDER= cdnPath + '/tmp/',
IMAGES_FOLDER= cdnPath + "/images/",
ALLOWED_EXTENSIONS=set(['jpg','jpeg','png']),
MAX_CONTENT_LENGTH=16 * 1024 * 1024,
historyFirstPagSize=,
historyPagSize=,
#time in minutes
loginMaxTime=20
convertBin='convert',
historyFirstPagSize=16,
historyPagSize=16,
loginMaxTime=20,

consumer_key= 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret= 'xxxxxxxxxxxxxxxxxxxx',
access_token= 'xxxxxxxxx',
access_token_secret= 'xxxxxxxxxxxxxxxxx',
hashtag = '#prueba',

geoserver_apirest='http://xxxxxxxxxxxxx/geoserver/rest',
geoserver_user='xxxxxxxxxxxx',
geoserver_psswd='xxxxxxxxxxxxxxxxxxx',
geoserver_ws='xxxx'
)
Empty file modified api/api/cons.py
100755 → 100644
Empty file.
103 changes: 103 additions & 0 deletions api/api/geoserverlayers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# -*- coding: utf-8 -*-

from geoserver.catalog import Catalog



class GeoserverLayers(object):

def __init__(self, gs_apirest, username, password):
try:
self.__catalog = Catalog(gs_apirest, username=username, password=password)

except Exception as err:
print("Geoserver API Rest Error: {0}".format(err))

def __createSldStyle(self, sldpath, stylename, ovwrt=False):
try:
styles_list = [st.name for st in self.__catalog.get_styles()]
if ovwrt or not stylename in styles_list:
with open(sldpath) as f:
self.__catalog.create_style(stylename, f.read(), overwrite=ovwrt)
else:
print("This style already exists...")

except Exception as err:
print("Geoserver API Rest Error creating new style: {0}".format(err))

def __rmvResources(self, rsrc):
"""
Removing resources
"""
self.__catalog.delete(rsrc)
self.__catalog.reload()

def rmvStyle(self, stylename):
"""
Remove style
"""
try:

style = self.__catalog.get_style(stylename)
self.__rmvResources(style)

except Exception as err:
print("Geoserver API Rest Error removing style: {0}".format(err))

def rmvDataStore(self, ds_store):
"""
Remove DataStore (with his layer)
"""
try:

lay_rm = self.__catalog.get_layer(ds_store)
self.__rmvResources(lay_rm)

str_rm = self.__catalog.get_store(ds_store)
self.__rmvResources(str_rm)

except Exception as err:
print("Geoserver API Rest Error removing data store: {0}".format(err))

def createGeoserverWMSLayer(self, data, ws_name, ds_name, stylename, sldpath, debug=False):
"""
Create Geoserver WMS layer
Status codes:
2 : "Geoserver layer successfully created"
-1 : "Workspace does not exist"
-2 : "Datastore already exists"
-3 : "Error creating Geoserver layer"
-4 : "File missing"
"""
try:

if not self.__catalog.get_workspace(ws_name):
print("Workspace does not exist")
return -1

ds_list = [i.name for i in self.__catalog.get_stores()]
if ds_name in ds_list:
print("Datastore already exists")
return -2

ds = self.__catalog.create_datastore(ds_name, ws_name)
ft = self.__catalog.create_featurestore(ds_name, workspace=ws_name,data=data)

print("Geoserver layer successfully created...")

self.__createSldStyle(sldpath, stylename)
lyr = self.__catalog.get_layer(ds_name)
lyr.enabled = True
lyr.default_style = stylename
self.__catalog.save(lyr)

if debug:
rsrc = self.__catalog.get_resource(ds_name, workspace=ws_name)
print("Data Store XML: {}".format(rsrc.href))

return 2

except Exception as err:
print("Geoserver API Rest Error creating new layer: {0}".format(err))
return -3
Loading

0 comments on commit f104a89

Please sign in to comment.