Merge remote-tracking branch 'github-miracl/rps-new-mobile-app'
diff --git a/servers/rps/config_default.py b/servers/rps/config_default.py
index 915efee..98896ef 100644
--- a/servers/rps/config_default.py
+++ b/servers/rps/config_default.py
@@ -113,6 +113,12 @@
 # rpsPrefix = 'rps'  # Default
 # setDeviceName = True
 
+"""Mobile client options"""
+# mobileUseNative = True # False by default
+serviceName = "Milagro MFA Demo"
+# serviceType = "online" # Default
+# serviceIconUrl = "http://example.com/icon.jpg"
+
 """Key value storage options"""
 storage = 'memory'
 
diff --git a/servers/rps/mobile_flow.py b/servers/rps/mobile_flow.py
new file mode 100644
index 0000000..27db65e
--- /dev/null
+++ b/servers/rps/mobile_flow.py
@@ -0,0 +1,106 @@
+import uuid
+import datetime
+
+from tornado.log import app_log as log
+from tornado.options import options
+
+from mpin_utils import secrets
+from mpin_utils.common import (
+    Time,
+)
+
+
+class MobileFlow:
+    """  Holds Bussines logic for the Mobile flow """
+
+    def __init__(self, application, storage):
+        self.application = application
+        self.storage = storage
+
+    def generate_wid(self):
+        # Generate request for MPinWIDServer for WID
+        wId = uuid.uuid4().hex
+
+        while wId is None or (self.storage.find(stage="auth", wid=wId)):
+            if wId is None:
+                log.debug("WebId is None".format(wId))
+            else:
+                log.debug("WebId {0} already exists. Generating a new one".format(wId))
+
+            wId = uuid.uuid4().hex
+            log.debug("New webId generated: {0}." .format(wId))
+
+        return wId
+
+    def generate_qr(self, wId):
+        webOTT = secrets.generate_ott(options.OTTLength, self.application.server_secret.rng, "hex")
+
+        nowTime = Time.syncedNow()
+        expirePinPadTime = nowTime + datetime.timedelta(seconds=options.accessNumberExpireSeconds)
+        expireTime = expirePinPadTime + datetime.timedelta(seconds=options.accessNumberExtendValiditySeconds)
+
+        self.storage.add(stage="auth", expire_time=expireTime, webOTT=webOTT, wid=wId)
+
+        qrUrl = options.rpsBaseURL + "#" + wId
+
+        params = {
+            "ttlSeconds": options.accessNumberExpireSeconds,
+            "qrUrl": qrUrl,
+            "webOTT": webOTT,
+            "localTimeStart": Time.DateTimetoEpoch(nowTime),
+            "localTimeEnd": Time.DateTimetoEpoch(expirePinPadTime)
+        }
+
+        return params
+
+    def update_app_status(self, data):
+        mobile_status = data.get('status')
+        params = {
+            'Status': 'OK'
+        }
+
+        # Keyfind
+        keyAuth = self.storage.find(stage="auth", wid=data.get('wid'))
+        if not keyAuth:
+            return params
+
+        userId = data.get('userId')
+
+        keyAuth.update(mobile_status=mobile_status, userId=userId)
+
+        if mobile_status == "wid":
+            params = {
+                'PrerollId': "",  # We don't use it at the moment
+                'AppName': options.serviceName,
+                'AppLogoUrl': options.serviceIconUrl,
+            }
+
+        return params
+
+    def get_app_status(self, webOTT):
+        params = {
+            'status':      "new",
+            'statusCode':  0,
+            'userId':      "",
+            'redirectURL': "",
+            'authOTT': ""
+        }
+
+        I = self.storage.find(stage="auth", webOTT=webOTT)
+        if not I:
+            log.debug("Cannot find webOTT: {0}".format(webOTT))
+            params['status'] = 'expired'
+            return params
+
+        if I.mobile_status:
+            params['status'] = I.mobile_status
+
+        if I.mobile_status == 'user' and I.userId:
+            params['userId'] = I.userId
+
+        authOTT = I.authOTT
+        if authOTT and (str(I.status) == "200"):
+            params['status'] = 'authenticate'
+            params['authOTT'] = authOTT
+
+        return params
diff --git a/servers/rps/rps.py b/servers/rps/rps.py
index 4dd9c6f..7ca8e0f 100755
--- a/servers/rps/rps.py
+++ b/servers/rps/rps.py
@@ -56,6 +56,8 @@
     process_dynamic_options,
 )
 
+from mobile_flow import MobileFlow
+
 if os.name == "posix":
     from mpDaemon import Daemon
 elif os.name == "nt":
@@ -99,7 +101,7 @@
 define("DTALocalURL", default="", type=unicode)
 
 # access number options
-define("accessNumberExpireSeconds", default=60, type=int)
+define("accessNumberExpireSeconds", default=300, type=int)
 define("accessNumberExtendValiditySeconds", default=5, type=int)
 define("accessNumberUseCheckSum", default=True, type=bool)
 
@@ -128,7 +130,11 @@
 # mobile client config
 define("mobileUseNative", default=False, type=bool)
 define("mobileConfig", default=None, type=list)
+define("mobileService", default=None, type=dict)
 define("useNFC", default=False, type=bool)
+define("serviceName", default="", type=unicode)
+define("serviceType", default="online", type=unicode)
+define("serviceIconUrl", default="", type=unicode)
 
 
 # Mapping between local names of dynamic options and names from json
@@ -139,6 +145,7 @@
     'time_synchronization_period': 'timePeriod',
     'mobile_use_native': 'mobileUseNative',
     'mobile_client_config': 'mobileConfig',
+    'mobile_service': 'mobileService',
 }
 
 
@@ -312,9 +319,13 @@
         }
 
         if not options.requestOTP:
-            params["accessNumberURL"] = "{0}/accessnumber".format(baseURL)
+            params["accessNumberURL"] = "{0}/access".format(baseURL)
             params["getAccessNumberURL"] = "{0}/getAccessNumber".format(baseURL)
 
+        if options.mobileUseNative:
+            params["getQrUrl"] = "{0}/getQrUrl".format(baseURL)
+            params["codeStatusURL"] = "{0}/codeStatus".format(baseURL)
+
         self.write(params)
         self.finish()
 
@@ -674,7 +685,7 @@
         # Generate request for MPinWIDServer for WID
         wId = secrets.generate_random_webid(self.application.server_secret.rng, options.accessNumberUseCheckSum)
 
-        while wId is None or (self.storage.find(stage="auth", webID=wId)):
+        while wId is None or (self.storage.find(stage="auth", wid=wId)):
             if wId is None:
                 log.debug("WebId is None".format(wId))
             else:
@@ -703,7 +714,18 @@
         self.finish()
 
 
-class RPSAccessNumberHandler(BaseHandler):
+class RPSGetQrUrlHandler(BaseHandler):
+    @tornado.web.asynchronous
+    @tornado.gen.engine
+    def post(self):
+        mobileFlow = MobileFlow(self.application, self.storage)
+        params = mobileFlow.generate_qr(mobileFlow.generate_wid())
+
+        self.write(params)
+        self.finish()
+
+
+class RPSAccessHanler(BaseHandler):
     @tornado.web.asynchronous
     @tornado.gen.engine
     def post(self):
@@ -717,25 +739,10 @@
             self.finish()
             return
 
-        I = self.storage.find(stage="auth", webOTT=webOTT)
-        if not I:
-            log.debug("Cannot find webOTT: {0}".format(webOTT))
+        params = MobileFlow(self.application, self.storage).get_app_status(webOTT)
 
-            self.set_status(404)
-            self.finish()
-            return
-
-        authOTT = I.authOTT
-        if authOTT and (str(I.status) == "200"):
-            self.write({"authOTT": authOTT})
-            self.finish()
-        else:
-            if not authOTT:
-                log.debug("authOTT not set for webOTT: {0}".format(webOTT))
-            else:
-                log.debug("Auth status for webOTT: {0}: {1}".format(webOTT, I.status))
-            self.set_status(401)
-            self.finish()
+        self.write(params)
+        self.finish()
 
 
 class RPSAuthenticateHandler(BaseHandler):
@@ -849,6 +856,18 @@
         self.finish()
 
 
+class ServiceHandler(BaseHandler):
+    @tornado.web.asynchronous
+    @tornado.gen.engine
+    def get(self):
+        if options.mobileService:
+            params = json.dumps(options.mobileService)
+            self.write(params)
+        else:
+            self.set_status(403)
+        self.finish()
+
+
 class DefaultHandler(BaseHandler):
     def get(self, input):
         reason = "URI NOT FOUND"
@@ -1493,6 +1512,34 @@
             self.write(json.dumps(options.mobileConfig))
 
 
+class RPSCodeStatusHandler(BaseHandler):
+    @tornado.web.asynchronous
+    @tornado.gen.engine
+    def post(self):
+        try:
+            data = json.loads(self.request.body)
+            data['status']
+        except ValueError:
+            log.error("Cannot decode body as JSON.")
+            log.debug(self.request.body)
+            self.set_status(400, reason="BAD REQUEST. INVALID JSON")
+            self.finish()
+            return
+        except KeyError:
+            log.error("Invalid JSON data structure")
+            log.debug(data)
+            self.set_status(400, reason="BAD REQUEST. INVALID DATA")
+            self.finish()
+            return
+
+        mobileFlow = MobileFlow(self.application, self.storage)
+        params = mobileFlow.update_app_status(data)
+
+        self.set_status(200, 'OK')
+        self.write(params)
+        self.finish()
+
+
 # MAIN
 class Application(tornado.web.Application):
     def __init__(self):
@@ -1503,8 +1550,10 @@
             (r"/{0}/signature/([0-9A-Fa-f]+)".format(rpsPrefix), RPSSignatureHandler),  # GET
             (r"/{0}/timePermit/([0-9A-Fa-f]+)".format(rpsPrefix), RPSTimePermitHandler),  # GET
             (r"/{0}/setupDone/([0-9A-Fa-f]+)".format(rpsPrefix), RPSSetupDoneHandler),  # POST
-            (r"/{0}/accessnumber".format(rpsPrefix), RPSAccessNumberHandler),  # POST
+            (r"/{0}/access".format(rpsPrefix), RPSAccessHanler),  # POST
             (r"/{0}/getAccessNumber".format(rpsPrefix), RPSGetAccessNumberHandler),  # POST
+            (r"/{0}/getQrUrl".format(rpsPrefix), RPSGetQrUrlHandler),  # POST
+            (r"/{0}/codeStatus".format(rpsPrefix), RPSCodeStatusHandler),  # POST
             (r"/{0}/clientSettings".format(rpsPrefix), ClientSettingsHandler),
             (r"/{0}/authenticate".format(rpsPrefix), RPSAuthenticateHandler),  # POST, for mobile login
             # Authentication
@@ -1518,6 +1567,7 @@
             (r"/loginResult", LoginResultHandler),  # POST
 
             (r"/status", StatusHandler),
+            (r"/service", ServiceHandler),  # GET
             (r"/dynamicOptions", DynamicOptionsHandler),  # POST, GET
             (r"/{0}/mobileConfig".format(rpsPrefix), MobileConfigHandler),  # GET
             (r"/(.*)", DefaultHandler),