Skip to content

Commit

Permalink
Add scala code formatter as an SBT plugin and an IntelliJ plugin (#987)
Browse files Browse the repository at this point in the history
Add scala linter and plugins to format scala code
  • Loading branch information
Dmitry Tverdokhleb authored and tsione committed Jan 9, 2019
1 parent 7b936f1 commit 08a0608
Show file tree
Hide file tree
Showing 256 changed files with 1,865 additions and 1,512 deletions.
5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/externalDependencies.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// https://scalameta.org/scalafmt/docs/configuration.html

maxColumn = 120
binPackImportSelectors = true
newlines.alwaysBeforeCurlyBraceLambdaParams = true
optIn.breakChainOnFirstMethodDot = false
continuationIndent.extendSite = 2
align.tokens = [
{code = "%", owner = "Term.ApplyInfix"},
{code = "%%", owner = "Term.ApplyInfix"}
]
align.openParenCallSite = false
align.openParenDefnSite = false
danglingParentheses = true
5 changes: 4 additions & 1 deletion modules/authentication/server-scala/build.sbt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
addCompilerPlugin("org.psywerx.hairyfotr" %% "linter" % "0.1.17")

lazy val authentication = project in file(".") dependsOn(modules.map(_ % "test->test; compile->compile"): _*)

Expand All @@ -6,4 +7,6 @@ lazy val modules = List(
ProjectRef(base = file("../../user/server-scala"), id = "user")
)

parallelExecution in test := false
parallelExecution in test := false
scalafmtOnCompile := true
scalafmtConfig := Some(file("../../.scalafmt.conf"))
1 change: 1 addition & 0 deletions modules/authentication/server-scala/project/plugin.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.5.1")
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ class AuthenticationModule extends ServerModule[UserContext, SchemaInitializer[_
linkedinAuthSchemaInitializer,
certificateAuthSchemaInitializer
)
override lazy val queries: mutable.HashSet[Field[UserContext, Unit]] = mutable.HashSet(authenticationSchema.queries: _*)
override lazy val mutations: mutable.HashSet[Field[UserContext, Unit]] = mutable.HashSet(authenticationSchema.mutations ++ tokenSchema.mutations: _*)
override lazy val extensions: mutable.HashSet[GraphQLSchemaExtension[UserContext]] = mutable.HashSet(authenticationSchema.extension)
override lazy val queries: mutable.HashSet[Field[UserContext, Unit]] =
mutable.HashSet(authenticationSchema.queries: _*)
override lazy val mutations: mutable.HashSet[Field[UserContext, Unit]] =
mutable.HashSet(authenticationSchema.mutations ++ tokenSchema.mutations: _*)
override lazy val extensions: mutable.HashSet[GraphQLSchemaExtension[UserContext]] =
mutable.HashSet(authenticationSchema.extension)

bindings = new AuthenticationBinding
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@ class AuthConfig @Inject()(config: Config) {
val scope: String = config.getString("oauth2.linkedin.scope")
val callback: String = config.getString("oauth2.linkedin.callback")
}
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package errors

case class Unauthenticated(msg: String = "") extends Error(msg)
case class Unauthenticated(msg: String = "") extends Error(msg)
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package errors

case class Unauthorized(msg: String = "") extends Error(msg)
case class Unauthorized(msg: String = "") extends Error(msg)
Original file line number Diff line number Diff line change
Expand Up @@ -28,98 +28,131 @@ object AuthenticationResolver extends ActorNamed {
final val name = "AuthenticationResolver"
}

class AuthenticationResolver @Inject()(userRepository: UserRepository,
jwtAuthService: JwtAuthService[JwtContent],
mailService: MailService[Message, MailPayload],
messageTemplateService: MessageTemplateService,
mailConfig: MailConfig,
authConfig: AuthConfig,
appConfig: AppConfig)
(implicit executionContext: ExecutionContext) extends Actor
class AuthenticationResolver @Inject()(
userRepository: UserRepository,
jwtAuthService: JwtAuthService[JwtContent],
mailService: MailService[Message, MailPayload],
messageTemplateService: MessageTemplateService,
mailConfig: MailConfig,
authConfig: AuthConfig,
appConfig: AppConfig
)(implicit executionContext: ExecutionContext)
extends Actor
with ActorLogging {

override def receive: Receive = {
case (input: RegisterUserInput, skipConfirmation: Boolean) => {
for {
createdUser <- userRepository.save(
User(
username = input.username,
email = input.email,
role = "user",
isActive = skipConfirmation,
password = BCrypt.hashpw(input.password, BCrypt.gensalt)
)).run
createdUser <- userRepository
.save(
User(
username = input.username,
email = input.email,
role = "user",
isActive = skipConfirmation,
password = BCrypt.hashpw(input.password, BCrypt.gensalt)
)
)
.run
mailingResult <- if (!skipConfirmation) {
mailService.send(
messageTemplateService.createConfirmRegistrationMessage(
createdUser,
appConfig.name,
mailConfig.address,
appConfig.url + "/confirmation/" + jwtAuthService.createAccessToken(JwtContent(createdUser.id.get)))
appConfig.url + "/confirmation/" + jwtAuthService.createAccessToken(JwtContent(createdUser.id.get))
)
)
} else Future.successful(MailPayload())
} yield UserPayload(Some(createdUser), mailingResult.errors)
}.recover {
case e: SQLException =>
val usernameWarning = if (e.getMessage.contains("column USERNAME is not unique")) Some(FieldError("username", "Username already exists.")) else None
val emailWarning = if (e.getMessage.contains("column EMAIL is not unique")) Some(FieldError("email", "E-mail already exists.")) else None
UserPayload(errors = Some(List(usernameWarning, emailWarning).flatten))
}.pipeTo(sender)
case e: SQLException =>
val usernameWarning =
if (e.getMessage.contains("column USERNAME is not unique"))
Some(FieldError("username", "Username already exists."))
else None
val emailWarning =
if (e.getMessage.contains("column EMAIL is not unique")) Some(FieldError("email", "E-mail already exists."))
else None
UserPayload(errors = Some(List(usernameWarning, emailWarning).flatten))
}
.pipeTo(sender)

case input: ResendConfirmationMessageInput => {
for {
user <- userRepository.findByUsernameOrEmail(input.usernameOrEmail).run failOnNone NotFound(s"User with username or email: [${input.usernameOrEmail}] not found.")
_ <- if (!user.isActive) Future.successful() else Future.failed(AlreadyExists(s"User with id: [${user.id}] is active"))
_ <- if (BCrypt.checkpw(input.password, user.password)) Future.successful() else Future.failed(Unauthenticated())
user <- userRepository.findByUsernameOrEmail(input.usernameOrEmail).run failOnNone NotFound(
s"User with username or email: [${input.usernameOrEmail}] not found."
)
_ <- if (!user.isActive) Future.successful()
else Future.failed(AlreadyExists(s"User with id: [${user.id}] is active"))
_ <- if (BCrypt.checkpw(input.password, user.password)) Future.successful()
else Future.failed(Unauthenticated())
accessToken = jwtAuthService.createAccessToken(JwtContent(user.id.get))
mailingResult <- mailService.send(
messageTemplateService.createConfirmRegistrationMessage(
user,
appConfig.name,
mailConfig.address,
appConfig.url + "/confirmation/" + accessToken)
appConfig.url + "/confirmation/" + accessToken
)
)
} yield UserPayload(Some(user), mailingResult.errors)
}.pipeTo(sender)

case input: LoginUserInput => {
for {
user <- userRepository.findByUsernameOrEmail(input.usernameOrEmail).run failOnNone NotFound(s"User with username or email: [${input.usernameOrEmail}] not found.")
_ <- if (BCrypt.checkpw(input.password, user.password)) Future.successful() else Future.failed(Unauthenticated())
user <- userRepository.findByUsernameOrEmail(input.usernameOrEmail).run failOnNone NotFound(
s"User with username or email: [${input.usernameOrEmail}] not found."
)
_ <- if (BCrypt.checkpw(input.password, user.password)) Future.successful()
else Future.failed(Unauthenticated())
accessToken = jwtAuthService.createAccessToken(JwtContent(user.id.get))
refreshToken = jwtAuthService.createRefreshToken(JwtContent(user.id.get), user.password)
} yield AuthPayload(Some(user), Some(Tokens(accessToken, refreshToken)))
}.recover {
case _: NotFound => AuthPayload(errors = Some(FieldError("usernameOrEmail", "Please enter a valid username or e-mail.") :: Nil))
case _: Unauthenticated => AuthPayload(errors = Some(FieldError("password", "Please enter a valid password.") :: Nil))
}.pipeTo(sender)
case _: NotFound =>
AuthPayload(errors = Some(FieldError("usernameOrEmail", "Please enter a valid username or e-mail.") :: Nil))
case _: Unauthenticated =>
AuthPayload(errors = Some(FieldError("password", "Please enter a valid password.") :: Nil))
}
.pipeTo(sender)

case input: ForgotPasswordInput => {
for {
user <- userRepository.findByEmail(input.email).run failOnNone NotFound(s"User with username or email: [${input.email}] not found.")
user <- userRepository.findByEmail(input.email).run failOnNone NotFound(
s"User with username or email: [${input.email}] not found."
)
token = jwtAuthService.createAccessToken(JwtContent(user.id.get))
_ <- mailService.send(
messageTemplateService.createRecoverPasswordMessage(
user,
appConfig.name,
mailConfig.address,
appConfig.url + "/reset-password/" + token)
appConfig.url + "/reset-password/" + token
)
)
} yield token
}.pipeTo(sender)

case input: ResetPasswordInput => {
if (input.password != input.passwordConfirmation)
if (input.password != input.passwordConfirmation)
Future.successful(ResetPayload(Some(FieldError("password", "Passwords are not the same.") :: Nil)))
else if (input.password.length < authConfig.passwordMinLength)
Future.successful(ResetPayload(Some(FieldError("password", s"Password length must be more than ${authConfig.passwordMinLength}.") :: Nil)))
else for {
tokenContent <- jwtAuthService.decodeAccessToken(input.token).asFuture
user <- userRepository.findOne(tokenContent.id).run failOnNone NotFound(s"User with id: [${tokenContent.id}] not found.")
_ <- userRepository.update(user.copy(password = BCrypt.hashpw(input.password, BCrypt.gensalt))).run
} yield ResetPayload()
Future.successful(
ResetPayload(
Some(FieldError("password", s"Password length must be more than ${authConfig.passwordMinLength}.") :: Nil)
)
)
else
for {
tokenContent <- jwtAuthService.decodeAccessToken(input.token).asFuture
user <- userRepository.findOne(tokenContent.id).run failOnNone NotFound(
s"User with id: [${tokenContent.id}] not found."
)
_ <- userRepository.update(user.copy(password = BCrypt.hashpw(input.password, BCrypt.gensalt))).run
} yield ResetPayload()
}.pipeTo(sender)

case unknownMessage@_ => log.warning(s"Received unknown message: $unknownMessage")
case unknownMessage @ _ => log.warning(s"Received unknown message: $unknownMessage")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,24 @@ object TokenResolver extends ActorNamed {
final val name = "TokensResolver"
}

class TokenResolver @Inject()(userRepository: UserRepository,
jwtAuthService: JwtAuthService[JwtContent])
(implicit executionContext: ExecutionContext) extends Actor
class TokenResolver @Inject()(userRepository: UserRepository, jwtAuthService: JwtAuthService[JwtContent])(
implicit executionContext: ExecutionContext
) extends Actor
with ActorLogging {

override def receive: Receive = {
case refreshToken: String => {
for {
tokenContent <- jwtAuthService.decodeContent(refreshToken).asFuture
user <- userRepository.findOne(tokenContent.id).run failOnNone NotFound(s"User with id: [${tokenContent.id}] not found.")
user <- userRepository.findOne(tokenContent.id).run failOnNone NotFound(
s"User with id: [${tokenContent.id}] not found."
)
_ <- jwtAuthService.decodeRefreshToken(refreshToken, user.password).asFuture
accessToken = jwtAuthService.createAccessToken(JwtContent(tokenContent.id))
refreshToken = jwtAuthService.createRefreshToken(JwtContent(tokenContent.id), user.password)
} yield Tokens(accessToken, refreshToken)
}.pipeTo(sender)

case unknownMessage@_ => log.warning(s"Received unknown message: $unknownMessage")
case unknownMessage @ _ => log.warning(s"Received unknown message: $unknownMessage")
}
}
}
Loading

0 comments on commit 08a0608

Please sign in to comment.