Beispiel #1
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/Wall/{wallId}")] HttpRequestMessage req, string wallId, TraceWriter log)
        {
            _log = log;

            if (IsAuthenticated)
            {
                auth = req.GetAuthInfoAsync(log).Result;
            }

            log.Info("Is Authenticated: " + IsAuthenticated);

            bool   isAdmin    = false;
            string realWallId = wallId;

            if (IsAuthenticated)
            {
                var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;
                var result = TableStorage.GetEntity <Tracked>(Constants.TableNames.Tracked, nameId, wallId);
                isAdmin = result != null;

                log.Info("isAdmin: " + isAdmin);
            }

            var tempTable = TableStorage.GetEntity <TemporaryUrl>(Constants.TableNames.TemporaryUrl, realWallId, realWallId);

            if (tempTable == null && !isAdmin)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }

            if (!isAdmin)
            {
                realWallId = tempTable.RealUrl;
            }

            if (isAdmin || tempTable.Expiry >= DateTime.UtcNow)
            {
                switch (req.Method.ToString())
                {
                case "GET":
                    return(req.CreateResponse(HttpStatusCode.OK, GetWall(realWallId)));

                case "POST":
                    return(await UpdateWall(req, realWallId));

                default:
                    return(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
                }
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.Forbidden)
                {
                    Content = new StringContent("F**k Off")
                });
            }
        }
Beispiel #2
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "api/location/{wallId}")] HttpRequestMessage req, TraceWriter log, string wallId)
        {
            log.Info("Is Authenticated: " + IsAuthenticated);

            var body = await req.Content.ReadAsStringAsync();

            var entity = JsonConvert.DeserializeObject <Request>(body);

            if (entity.Latitude < -90 || entity.Latitude > 90 || entity.Longitude < -180 || entity.Longitude > 180 || entity.Distance <= 0)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            auth = req.GetAuthInfoAsync(log).Result;

            var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;

            var result = TableStorage.GetEntity <Walls>(Constants.TableNames.Walls, wallId, wallId);

            if (result == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }

            result.Latitude    = entity.Latitude;
            result.Longitude   = entity.Longitude;
            result.MaxDistance = entity.Distance;

            TableStorage.Insert(Constants.TableNames.Walls, result);

            return(req.CreateResponse(HttpStatusCode.OK));
        }
Beispiel #3
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/dashboard")] HttpRequestMessage request, TraceWriter log)
        {
            log.Info("Is Authenticated: " + IsAuthenticated);

            if (!IsAuthenticated)
            {
                return(request.CreateErrorResponse(HttpStatusCode.Forbidden, "These are not the droids you're looking for"));
            }

            auth = request.GetAuthInfoAsync(log).Result;

            var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;

            var trackedWalls = TableStorage.QueryByPartitionKey <Tracked>(Constants.TableNames.Tracked, nameId);

            List <Walls> walls = new List <Walls>();

            foreach (var wall in trackedWalls)
            {
                var entity = TableStorage.GetEntity <Walls>(Constants.TableNames.Walls, wall.RowKey, wall.RowKey);

                if (entity.Deleted != true)
                {
                    walls.Add(entity);
                }
            }

            var json = JsonConvert.SerializeObject(walls);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json)
            });
        }
Beispiel #4
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/admin/qrCode/{wallId}")]
                                              HttpRequestMessage request, TraceWriter log, string wallId)
        {
            if (!IsAuthenticated)
            {
                return(request.CreateErrorResponse(HttpStatusCode.Forbidden, "These are not the droids you're looking for"));
            }

            auth = request.GetAuthInfoAsync(log).Result;

            log.Info("Is Authenticated: " + IsAuthenticated);

            var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;

            var trackedWalls = TableStorage.QueryByPartitionKey <Tracked>(Constants.TableNames.Tracked, nameId);

            if (trackedWalls == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }

            var path = $"{wallId}/qrCode";

            log.Info("Getting blob: " + path);

            var blob = BlobStorage.GetBlob(Constants.BlobContainerNames.Wall, path);

            var ms = new MemoryStream();

            try
            {
                blob.DownloadToStream(ms);
            } catch (WebException e)
            {
                log.Error(e.Message);
                return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, "QrCode not found"));
            }

            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ByteArrayContent(ms.ToArray());
            response.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue(CONTENT_DISPOSITION_TYPE);
            response.Content.Headers.ContentDisposition.FileName = FILENAME;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(MEDIA_TYPE);

            return(response);
        }
Beispiel #5
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/{wallId}/IsGeolocated")] HttpRequestMessage request, TraceWriter log, string wallId)
        {
            if (IsAuthenticated)
            {
                auth = request.GetAuthInfoAsync(log).Result;
            }

            log.Info("Is Authenticated: " + IsAuthenticated);

            bool   isAdmin    = false;
            string realWallId = wallId;

            //if admin ignore geo location
            if (IsAuthenticated)
            {
                var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;
                var result = TableStorage.GetEntity <Tracked>(Constants.TableNames.Tracked, nameId, wallId);
                isAdmin = result != null;

                log.Info("isAdmin: " + isAdmin);
            }

            var tempTable = TableStorage.GetEntity <TemporaryUrl>(Constants.TableNames.TemporaryUrl, wallId, wallId);

            if (tempTable == null && !isAdmin)
            {
                return(request.CreateResponse(HttpStatusCode.NotFound, "There's no wall here"));
            }

            if (!isAdmin)
            {
                realWallId = tempTable.RealUrl;
            }

            var location = TableStorage.GetEntity <Walls>(Constants.TableNames.Walls, realWallId, realWallId);

            if (location == null)
            {
                return(request.CreateResponse(HttpStatusCode.OK, new { IsGeolocated = false }));
            }

            return(request.CreateResponse(HttpStatusCode.OK, new { IsGeolocated = true }));
        }
Beispiel #6
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/Generate/Image")] HttpRequestMessage request, TraceWriter log, ExecutionContext context)
        {
            if (IsAuthenticated)
            {
                auth = request.GetAuthInfoAsync(log).Result;
            }

            log.Info("Is Authenticated: " + IsAuthenticated);

            //We can zip a bunch of them
            var generator = new UrlGenerator(new Uri(QrCodeUrl), 1);
            var guid      = generator.Guids.First();

            //Create Blob/Table references
            var wallPath = string.Format($"{guid.ToString("N")}/wall");

            var wallblob = BlobStorage.GetBlob(Constants.BlobContainerNames.Wall, wallPath);

            var contents = new WallEntity(new Message()
            {
                Text = Constants.Default.Wall.WelcomeMessage, Username = Constants.Default.Wall.User
            });

            var json = JsonConvert.SerializeObject(contents);

            wallblob.UploadText(json);

            if (IsAuthenticated)
            {
                var name   = auth.GetClaim(ClaimTypes.Name).Value;
                var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;
                var user   = new Users(name, nameId);
                TableStorage.Insert(Constants.TableNames.Users, user);

                var trackedWall = new Tracked(nameId, guid.ToString("N"));
                TableStorage.Insert(Constants.TableNames.Tracked, trackedWall);
            }

            var urls = generator.ToUri();

            var bitmap = new QrCode().GenerateImage(urls.First(), 10);

            var ms = new MemoryStream();

            bitmap.Save(ms, ImageFormat.Png);

            var logoPath   = context.FunctionAppDirectory + logoLocation;
            var footerPath = context.FunctionAppDirectory + footerLocation;
            var logo       = new Logo(logoPath);
            var footer     = new Logo(footerPath);

            ms.Position = 0;

            var qrCodeWithLogo = logo.Image.AppendImage(Image.FromStream(ms), 10, 10);

            ms.Position = 0;

            var footerImage = qrCodeWithLogo.AppendImage(footer.Image, 0, 0);

            var result = footerImage.WriteText(guid.ToString("N").Substring(0, 5), new PointF(40, footerImage.Height - 160));

            var msreadathon = new MemoryStream();

            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);

            Encoder           myEncoder           = Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter  myEncoderParameter  = new EncoderParameter(myEncoder, 100L);

            myEncoderParameters.Param[0] = myEncoderParameter;

            result.Save(msreadathon, jpgEncoder, myEncoderParameters);

            //Save image to blob
            var qrCodePath = string.Format($"{guid.ToString("N")}/qrCode");

            var container = BlobStorage.GetContainer(Constants.BlobContainerNames.Wall);

            var qrCodeBlob = container.GetBlockBlobReference(qrCodePath);

            qrCodeBlob.Properties.ContentType = "image/png";

            ms.Position = 0;

            qrCodeBlob.UploadFromStream(ms);

            log.Info("Image uploaded to: " + qrCodeBlob.Uri.AbsoluteUri);

            var response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ByteArrayContent(msreadathon.ToArray());
            response.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue(CONTENT_DISPOSITION_TYPE);
            response.Content.Headers.ContentDisposition.FileName = FILENAME;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(MEDIA_TYPE);
            return(response);
        }
Beispiel #7
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/generate")] HttpRequestMessage req, TraceWriter log)
        {
            if (IsAuthenticated)
            {
                auth = req.GetAuthInfoAsync(log).Result;
            }

            log.Info("Is Authenticated: " + IsAuthenticated);

            var queryTracked = req.GetQueryValue("tracked");

            var title = req.GetQueryValue("title");

            var queryLogo = req.GetQueryValue("logo");

            var queryLatitude = req.GetQueryValue("latitude");

            var queryLongitude = req.GetQueryValue("longitude");

            var queryWallToken = req.GetQueryValue("wallToken");

            var wallToken = DecryptWallToken(queryWallToken);

            var isTracked = Boolean.TryParse(queryTracked, out bool tracked);

            var logoParsed = Boolean.TryParse(queryTracked, out bool hasLogo);

            var isLatitude = double.TryParse(queryLatitude, out double latitude);

            var isLongitude = double.TryParse(queryLongitude, out double longitude);

            var isWallId = Guid.TryParse(wallToken, out Guid wallId);

            //There's no validation on the values
            if (!isTracked || !logoParsed || (!isLatitude && queryLatitude != null) || (!isLongitude && queryLongitude != null) || !isWallId)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var wallPath = string.Format($"{wallId.ToString("N")}/wall");

            var wallblob = BlobStorage.GetBlob(Constants.BlobContainerNames.Wall, wallPath);

            var contents = new WallEntity(new Message {
                Text = Constants.Default.Wall.WelcomeMessage, Username = Constants.Default.Wall.User
            });

            var json = JsonConvert.SerializeObject(contents);

            wallblob.UploadText(json);

            var wall = new Walls(wallId.ToString("N"), latitude, longitude, title);

            TableStorage.Insert(Constants.TableNames.Walls, wall);

            var host = req.GetHost();

            var generator = new UrlGenerator(new Uri(host + path), 1);

            var uri = generator.ToUri().First();

            var bitmap = new QrCode().GenerateImage(uri, 50);

            var qrCodePath = string.Format($"{wallId.ToString("N")}/qrCode");

            var container = BlobStorage.GetContainer(Constants.BlobContainerNames.Wall);

            var qrCodeBlob = container.GetBlockBlobReference(qrCodePath);

            qrCodeBlob.Properties.ContentType = "image/jpeg";

            var ms = new MemoryStream();

            bitmap.Save(ms, ImageFormat.Jpeg);

            qrCodeBlob.UploadFromStream(ms);

            log.Info("Image uploaded to: " + qrCodeBlob.Uri.AbsoluteUri);

            if (tracked && IsAuthenticated)
            {
                var name   = auth.GetClaim(ClaimTypes.Name).Value;
                var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;
                var user   = new Users(name, nameId);
                TableStorage.Insert(Constants.TableNames.Users, user);

                var trackedWall = new Tracked(nameId, wallId.ToString("N"));
                TableStorage.Insert(Constants.TableNames.Tracked, trackedWall);
            }

            if (tracked)
            {
                return(req.CreateResponse(HttpStatusCode.OK, new { Created = DateTime.UtcNow, WallId = wallId.ToString("N") }));
            }
            else
            {
                return(req.CreateResponse(HttpStatusCode.OK, new { Created = DateTime.UtcNow }));
            }
        }
Beispiel #8
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "api/{wallId}/IsWithinDistance")] HttpRequestMessage request, TraceWriter log, string wallId)
        {
            if (IsAuthenticated)
            {
                auth = request.GetAuthInfoAsync(log).Result;
            }

            log.Info("Is Authenticated: " + IsAuthenticated);

            var queryLatitude = request.GetQueryValue("latitude");

            var queryLongtitude = request.GetQueryValue("longitude");

            var isLatitude = double.TryParse(queryLatitude, out double latitude);

            var isLongtitude = double.TryParse(queryLongtitude, out double longitude);

            if (!isLatitude || !isLongtitude || latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            log.Info("Client\n Latitude: " + latitude + "\nLongitude: " + longitude);

            bool   isAdmin    = false;
            string realWallId = wallId;

            if (IsAuthenticated)
            {
                var nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;
                var result = TableStorage.GetEntity <Tracked>(Constants.TableNames.Tracked, nameId, wallId);
                isAdmin = result != null;

                log.Info("isAdmin: " + isAdmin);
            }

            var tempTable = TableStorage.GetEntity <TemporaryUrl>(Constants.TableNames.TemporaryUrl, wallId, wallId);

            if (tempTable == null && !isAdmin)
            {
                return(request.CreateResponse(HttpStatusCode.NotFound, "There's no wall here"));
            }

            if (!isAdmin)
            {
                realWallId = tempTable.RealUrl;
            }

            var wall = TableStorage.GetEntity <Walls>(Constants.TableNames.Walls, realWallId, realWallId);

            if (wall.Latitude == 0 && wall.Longitude == 0)
            {
                return(request.CreateResponse(HttpStatusCode.OK, new { IsGeolocated = false, Message = "There is no location data for this wall" }));
            }

            log.Info("QR Code\n Latitude: " + wall.Latitude + "\nLongitude: " + wall.Longitude);

            var myCoord   = new GeoCoordinate(latitude, longitude);
            var wallCoord = new GeoCoordinate(wall.Latitude, wall.Longitude);

            //Haversine formula
            var distance = myCoord.GetDistanceTo(wallCoord);

            log.Info("Distance from client to QR code: " + distance + " meters");

            if (distance > wall.MaxDistance && !isAdmin)
            {
                return(request.CreateResponse(HttpStatusCode.OK, new { IsGeolocated = true, IsWithinDistance = false, Message = "You're outside the geo-location" }));
            }

            //Todo, consider revising the way 'IsAdmin' works in the entire application
            if (distance > wall.MaxDistance && isAdmin)
            {
                return(request.CreateResponse(HttpStatusCode.OK, new { IsAdmin = true, IsGeolocated = true, IsWithinDistance = false, Distance = distance, wall.MaxDistance, Message = "You're outside the geo-location" }));
            }

            if (isAdmin)
            {
                return(request.CreateResponse(HttpStatusCode.OK, new { IsAdmin = true, IsGeolocated = true, IsWithinDistance = true, Distance = distance, wall.MaxDistance }));
            }

            return(request.CreateResponse(HttpStatusCode.OK, new { IsGeolocated = true, IsWithinDistance = true }));
        }
Beispiel #9
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "api/image/{wallId}")]
            HttpRequestMessage req, string wallId, TraceWriter log)
        {
            if (IsAuthenticated)
            {
                auth = req.GetAuthInfoAsync(log).Result;
            }

            log.Info("Is Authenticated: " + IsAuthenticated);

            if (!req.Content.IsMimeMultipartContent())
            {
                return(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var multipart = await req.Content.ReadAsMultipartAsync();

            var content = multipart.Contents.First();

            var stream = await content.ReadAsStreamAsync();

            var filename = "no-filename";

            if (content.Headers.ContentDisposition.FileName != null)
            {
                filename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
            }

            if (content.Headers.ContentLength == 0)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
            if (filename.Length > 500)
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest)
                       {
                           Content = new StringContent("filename above 500 characters")
                       }
            }
            ;

            Image image;

            try
            {
                image = Image.FromStream(stream);
            }
            catch (Exception)
            {
                log.Error("An invalid filetype was attempted to be uploaded.");
                return(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var result = TableStorage.GetEntity <TemporaryUrl>(Constants.TableNames.TemporaryUrl, wallId, wallId);

            if (result == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotFound));
            }

            if (result.Expiry <= DateTime.UtcNow)
            {
                return new HttpResponseMessage(HttpStatusCode.Forbidden)
                       {
                           Content = new StringContent("F**k Off")
                       }
            }
            ;

            var container = BlobStorage.GetContainer(Constants.BlobContainerNames.Image);

            //Allow public access to this container - 'images'
            await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });

            var folder = result.RealUrl;

            var prefix = DateTime.UtcNow.ToString(DateTimeFormat) + "_";

            var path = string.Format($"{folder}/{prefix}{filename}");

            var blob = container.GetBlockBlobReference(path);

            blob.Properties.ContentType = content.Headers.ContentType.ToString();

            stream.Position = 0;

            blob.UploadFromStream(stream);

            //Get Blob Url and add it to the post.

            var uri = blob.Uri.AbsoluteUri;

            //This is copied in Wall (text)

            var name   = "";
            var nameId = "";

            if (IsAuthenticated && auth != null)
            {
                name = auth.GetClaim(ClaimTypes.GivenName).Value;

                nameId = auth.GetClaim(ClaimTypes.NameIdentifier).Value;
            }

            log.Info("Name: " + name);

            var wall = BlobStorage.GetWall(result.RealUrl);

            var wallMessage = new Message {
                ImageUri = uri, Filename = filename, Username = name, NameId = nameId
            };

            wall.Messages.Add(wallMessage);

            var block = BlobStorage.GetBlob(Constants.BlobContainerNames.Wall, $"{result.RealUrl}/wall");

            var json = JsonConvert.SerializeObject(wall);

            block.UploadText(json);

            wallMessage.SendToSlack(result.RealUrl);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json)
            });
        }
    }
}