<commit_before>//
//  AdminRouterCollection.swift
//  ivsa
//
//  Created by Light Dream on 01/12/2016.
//
//

import Foundation
import Auth
import Turnstile
import Vapor
import HTTP
import Routing

class AdminRouteCollection: RouteCollection {
    
    typealias Wrapped = HTTP.Responder
    
    private var authMiddleware: AdminAuthMiddleware
    
    
    init(authMiddleware: AdminAuthMiddleware) {
        self.authMiddleware = authMiddleware
    }
    
    
    func build<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
        let adminRouteBuilder = builder.grouped("admin")
        let adminProtectedRouteBuilder = adminRouteBuilder.grouped(self.authMiddleware)
        
        adminRouteBuilder.post("login") { request in
            
            guard let username = request.json?["email"]?.string,
                let password = request.json?["password"]?.string else {
                    throw GeneralErrors.missingParams.vaporError
            }
            
            let credentials = UsernamePassword(username: username, password: password)
            
            return try request.adminAuth.login(credentials)
        }
        
        adminRouteBuilder.get("makenouradmin") { request in
            
            let credentials = UsernamePassword(username: "<EMAIL>", password: "<PASSWORD>")
            var admin = IVSAAdmin(credentials: credentials)
            try admin.save()
            
            return admin
        }
        
        
        adminRouteBuilder.get("me") { request in
            return try request.admin()
        }
        
        adminRouteBuilder.get("testemail") { request in
            
            var user = IVSAUser()
            user.email = "<EMAIL>"
            try MailgunClient.sendAcceptanceEmail(toUser: user, baseURL: request.baseURL)
            
            return try JSON(node: ["ok": "awesome"])
        }
        
        // accepted values for :application_status param are:
        // inReview
        // accepted
        // rejected
        adminProtectedRouteBuilder.get("delegates", ":application_status") { request in
            let appStatus = try request.parameters.extract("application_status") as String
            let users: [IVSAUser] =  try IVSAUser.query().filter("application_status", appStatus).run()
            
            let sortedApplicants = users.filter { $0.registrationDetails != nil }.sorted(by: { (first, second) -> Bool in
                
                // we can force unwrap safely coz we filter first
                return first.registrationDetails!.ivsaChapter.country < second.registrationDetails!.ivsaChapter.country
            })
            let applicantsNode = try Node(node: sortedApplicants)
            
            let json = try JSON(node: applicantsNode)
            
            return json
        }
        
        adminProtectedRouteBuilder.get("applicant", IVSAUser.self) { request, user in
            return try JSON(node: try user.makeNode())
        }

        
        
        //        adminProtectedRouteBuilder.post("accept", IVSAUser.self) { request, user in
//            user.applicationStatus = .accepted
//            
//            var user = user
//            try user.save()
//            let node = try user.makeNode()
//            return try JSON(node: node)
//        }
//        
//        adminProtectedRouteBuilder.post("reject", IVSAUser.self) { request, user in
//            user.applicationStatus = .rejected
//            
//            var user = user
//            try user.save()
//            
//            return try JSON(node: try user.makeNode())
//        }
        
        adminProtectedRouteBuilder.post("updatePass", IVSAUser.self) { request, user in
            
            guard let newPass = request.json?["newPass"]?.string else {
                throw Abort.custom(status: .badRequest, message: "Missing param")
            }<commit_msg>reactivate accept/reject delegate and send emails<commit_after>//
//  AdminRouterCollection.swift
//  ivsa
//
//  Created by Light Dream on 01/12/2016.
//
//

import Foundation
import Auth
import Turnstile
import Vapor
import HTTP
import Routing

class AdminRouteCollection: RouteCollection {
    
    typealias Wrapped = HTTP.Responder
    
    private var authMiddleware: AdminAuthMiddleware
    
    
    init(authMiddleware: AdminAuthMiddleware) {
        self.authMiddleware = authMiddleware
    }
    
    
    func build<B: RouteBuilder>(_ builder: B) where B.Value == Wrapped {
        let adminRouteBuilder = builder.grouped("admin")
        let adminProtectedRouteBuilder = adminRouteBuilder.grouped(self.authMiddleware)
        
        adminRouteBuilder.post("login") { request in
            
            guard let username = request.json?["email"]?.string,
                let password = request.json?["password"]?.string else {
                    throw GeneralErrors.missingParams.vaporError
            }
            
            let credentials = UsernamePassword(username: username, password: password)
            
            return try request.adminAuth.login(credentials)
        }
        
        adminRouteBuilder.get("makenouradmin") { request in
            
            let credentials = UsernamePassword(username: "<EMAIL>", password: "<PASSWORD>")
            var admin = IVSAAdmin(credentials: credentials)
            try admin.save()
            
            return admin
        }
        
        
        adminRouteBuilder.get("me") { request in
            return try request.admin()
        }
        
        adminRouteBuilder.get("testemail") { request in
            
            var user = IVSAUser()
            user.email = "<EMAIL>"
            try MailgunClient.sendAcceptanceEmail(toUser: user, baseURL: request.baseURL)
            
            return try JSON(node: ["ok": "awesome"])
        }
        
        // accepted values for :application_status param are:
        // inReview
        // accepted
        // rejected
        adminProtectedRouteBuilder.get("delegates", ":application_status") { request in
            let appStatus = try request.parameters.extract("application_status") as String
            let users: [IVSAUser] =  try IVSAUser.query().filter("application_status", appStatus).run()
            
            let sortedApplicants = users.filter { $0.registrationDetails != nil }.sorted(by: { (first, second) -> Bool in
                
                // we can force unwrap safely coz we filter first
                return first.registrationDetails!.ivsaChapter.country < second.registrationDetails!.ivsaChapter.country
            })
            let applicantsNode = try Node(node: sortedApplicants)
            
            let json = try JSON(node: applicantsNode)
            
            return json
        }
        
        adminProtectedRouteBuilder.get("applicant", IVSAUser.self) { request, user in
            return try JSON(node: try user.makeNode())
        }

        
        
        adminProtectedRouteBuilder.post("accept", IVSAUser.self) { request, user in
            user.applicationStatus = .accepted
            
            var user = user
            try user.save()
            let node = try user.makeNode()
            
            do {
                try MailgunClient.sendAcceptanceEmail(toUser: user, baseURL: request.baseURL)
            } catch { }  // do nothing here!!!! we don't want the whole request to fail just because the mail client failed to initialize or send an email or whatever -_-
            
            return try JSON(node: node)
        }
        
        adminProtectedRouteBuilder.post("reject", IVSAUser.self) { request, user in
            user.applicationStatus = .rejected
            
            var user = user
            try user.save()
            
            do {
                try MailgunClient.sendRejectionEmail(toUser: user, baseURL: request.baseURL)
            } catch { }  // do nothing here!!!! we don't want the whole request to fail just because the mail client failed to initialize or send an email or whatever -_-
            
            
            return try JSON(node: try user.makeNode())
        }
        
        adminProtectedRouteBuilder.post("updatePass", IVSAUser.self) { request, user in
            
            guard let newPass = request.json?["newPass"]?.string else {
                throw Abort.custom(status: .badRequest, message: "Missing param")
            }
{'fraction_non_alphanumeric': 0.08882859502182376, 'fraction_numerical': 0.00212339270968503, 'mean_word_length': 1.758867556134071, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '351776', 'n_tokens_mistral': 2120, 'n_tokens_neox': 2085, 'n_words': 537}