<commit_before>package dsmoq.controllers

import org.json4s._
import org.json4s.jackson.JsonMethods
import org.scalatra.ScalatraServlet
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json.JacksonJsonSupport
import dsmoq.services._
import scala.util.{Success, Failure}
import org.scalatra.servlet.FileUploadSupport
import dsmoq.services.data.LoginData._
import dsmoq.services.data.DatasetData._
import dsmoq.services.data.GroupData._
import dsmoq.forms._
import dsmoq.AppConf
import dsmoq.services.data.ProfileData.UpdateProfileParams
import dsmoq.exceptions.{InputValidationException, NotFoundException, NotAuthorizedException}
import com.sun.corba.se.spi.orbutil.fsm.Input
import scala.util.control.Exception._

class ApiController extends ScalatraServlet
    with JacksonJsonSupport with SessionTrait with FileUploadSupport {
  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  before("/*") {
    if (!isValidSession()) {
      if (!((request.getRequestURI == "/api/profile" && request.getMethod == "GET") ||
          (request.getRequestURI == "/api/licenses" && request.getMethod == "GET") ||
          (request.getRequestURI == "/api/accounts" && request.getMethod == "GET") ||
          (request.getRequestURI == "/api/suggests/attributes" && request.getMethod == "GET"))) {
        cookies.get(sessionId) match {
          case Some(x) =>
            clearSessionCookie()
            halt(body = AjaxResponse("Unauthorized"))
          case None => // do nothing
        }
      }
    }
  }

  get("/*") {
    throw new Exception("err")
  }

  // JSON API
  get("/profile") {
    getUserInfoFromSession() match {
      case Success(x) => AjaxResponse("OK", x)
      case Failure(e) => AjaxResponse("NG")
    }
  }

  post("/profile") {
    val name = params.get("name")
    val fullname = params.get("fullname")
    val organization = params.get("organization")
    val title = params.get("title")
    val description = params.get("description")
    val image = fileParams.get("image")

    if (!isValidSession()) halt(body = AjaxResponse("Unauthorized"))

    val response = for {
      userInfo <- getUserInfoFromSession()
      facadeParams = UpdateProfileParams(name, fullname, organization, title, description, image)
      user <- AccountService.updateUserProfile(userInfo, facadeParams)
    } yield {
      setUserInfoToSession(user)
      AjaxResponse("OK", user)
    }
    response match {
      case Success(x) => x
      case Failure(e) =>
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse("NG")
        }
    }
  }

  post("/profile/email_change_requests") {
    val email = params.get("email")

    if (!isValidSession()) halt(body = AjaxResponse("Unauthorized"))

    (for {
      userInfo <- getUserInfoFromSession()
      user <- AccountService.changeUserEmail(userInfo, email)
    } yield {
      setUserInfoToSession(user)
    }) match {
      case Success(x) => AjaxResponse("OK")
      case Failure(e) =>
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse("NG")
        }
    }
  }

  put("/profile/password") {
    val currentPassword = params.get("current_password")
    val newPassword = params.get("new_password")

    if (!isValidSession()) halt(body = AjaxResponse("Unauthorized"))

    val response = for {
      userInfo <- getUserInfoFromSession()
      result <- AccountService.changeUserPassword(userInfo, currentPassword, newPassword)
    } yield {
      result
    }
    response match {
      case Success(x) => AjaxResponse("OK")
      case Failure(e) =>
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse("NG")
        }
    }
  }

  post("/signin") {
    val id = params.get("id")
    val password = params.get("password")
    val facadeParams = SigninParams(id, password)
    AccountService.getAuthenticatedUser(facadeParams) match {
      case Success(x) =>
        setUserInfoToSession(x)
        AjaxResponse("OK", getUserInfoFromSession().get)
      case Failure(e) =>
        clearSession()
        clearSessionCookie()
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse ("NG")
        }
    }
  }

  post("/signout") {
    clearSession()
    clearSessionCookie()
    AjaxResponse("OK", getUserInfoFromSession().get)
  }

  // dataset JSON API
  post("/datasets") {
    val files = fileMultiParams.get("file[]")
<commit_msg>[Server]サインインAPIのJSON API対応<commit_after>package dsmoq.controllers

import org.json4s._
import org.json4s.jackson.JsonMethods
import org.scalatra.ScalatraServlet
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json.JacksonJsonSupport
import dsmoq.services._
import scala.util.{Success, Failure}
import org.scalatra.servlet.FileUploadSupport
import dsmoq.services.data.LoginData._
import dsmoq.services.data.DatasetData._
import dsmoq.services.data.GroupData._
import dsmoq.forms._
import dsmoq.AppConf
import dsmoq.services.data.ProfileData.UpdateProfileParams
import dsmoq.exceptions.{InputValidationException, NotFoundException, NotAuthorizedException}
import com.sun.corba.se.spi.orbutil.fsm.Input
import scala.util.control.Exception._

class ApiController extends ScalatraServlet
    with JacksonJsonSupport with SessionTrait with FileUploadSupport {
  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  before("/*") {
    if (!isValidSession()) {
      if (!((request.getRequestURI == "/api/profile" && request.getMethod == "GET") ||
          (request.getRequestURI == "/api/licenses" && request.getMethod == "GET") ||
          (request.getRequestURI == "/api/accounts" && request.getMethod == "GET") ||
          (request.getRequestURI == "/api/suggests/attributes" && request.getMethod == "GET"))) {
        cookies.get(sessionId) match {
          case Some(x) =>
            clearSessionCookie()
            halt(body = AjaxResponse("Unauthorized"))
          case None => // do nothing
        }
      }
    }
  }

  get("/*") {
    throw new Exception("err")
  }

  // JSON API
  get("/profile") {
    getUserInfoFromSession() match {
      case Success(x) => AjaxResponse("OK", x)
      case Failure(e) => AjaxResponse("NG")
    }
  }

  post("/profile") {
    val name = params.get("name")
    val fullname = params.get("fullname")
    val organization = params.get("organization")
    val title = params.get("title")
    val description = params.get("description")
    val image = fileParams.get("image")

    if (!isValidSession()) halt(body = AjaxResponse("Unauthorized"))

    val response = for {
      userInfo <- getUserInfoFromSession()
      facadeParams = UpdateProfileParams(name, fullname, organization, title, description, image)
      user <- AccountService.updateUserProfile(userInfo, facadeParams)
    } yield {
      setUserInfoToSession(user)
      AjaxResponse("OK", user)
    }
    response match {
      case Success(x) => x
      case Failure(e) =>
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse("NG")
        }
    }
  }

  post("/profile/email_change_requests") {
    val email = params.get("email")

    if (!isValidSession()) halt(body = AjaxResponse("Unauthorized"))

    (for {
      userInfo <- getUserInfoFromSession()
      user <- AccountService.changeUserEmail(userInfo, email)
    } yield {
      setUserInfoToSession(user)
    }) match {
      case Success(x) => AjaxResponse("OK")
      case Failure(e) =>
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse("NG")
        }
    }
  }

  put("/profile/password") {
    val currentPassword = params.get("current_password")
    val newPassword = params.get("new_password")

    if (!isValidSession()) halt(body = AjaxResponse("Unauthorized"))

    val response = for {
      userInfo <- getUserInfoFromSession()
      result <- AccountService.changeUserPassword(userInfo, currentPassword, newPassword)
    } yield {
      result
    }
    response match {
      case Success(x) => AjaxResponse("OK")
      case Failure(e) =>
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse("NG")
        }
    }
  }

  post("/signin") {
    val data = params.get("d").map(x => {
      JsonMethods.parse(x).extract[SigninParams]
    }).getOrElse {
      SigninParams(None, None)
    }

    AccountService.getAuthenticatedUser(data) match {
      case Success(x) =>
        setUserInfoToSession(x)
        AjaxResponse("OK", getUserInfoFromSession().get)
      case Failure(e) =>
        clearSession()
        clearSessionCookie()
        e match {
          case e: InputValidationException => AjaxResponse("BadRequest", e.getErrorMessage())
          case _ => AjaxResponse ("NG")
        }
    }
  }

  post("/signout") {
    clearSession()
    clearSessionCookie()
    AjaxResponse("OK", getUserInfoFromSession().get)
  }

  // dataset JSON API
  post("/datasets") {
    val files = fileMultiParams.get("file[]")

{'fraction_non_alphanumeric': 0.12957894736842104, 'fraction_numerical': 0.0006315789473684211, 'mean_word_length': 3.093494183541577, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 44, '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': '3869870', 'n_tokens_mistral': 2828, 'n_tokens_neox': 2743, 'n_words': 552}