Skip to content

Commit

Permalink
Merge branch 'cooperlyt:master' into bugfix/block-unknown-phonenumbers
Browse files Browse the repository at this point in the history
  • Loading branch information
mapidentity authored Jul 2, 2024
2 parents 2644f3c + 353095b commit 05a50df
Show file tree
Hide file tree
Showing 8 changed files with 244 additions and 3 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/mavenpublish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Maven Package

on:
release:
types: [released]
push:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Set up JDK 18
uses: actions/setup-java@v1
with:
java-version: 18
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file

- name: Test
run: mvn clean test

- name: Build with Maven
run: mvn -B package --file pom.xml

- name: Publish to GitHub Packages Apache Maven
run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml
env:
GITHUB_TOKEN: ${{ github.token }}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import cc.coopersoft.keycloak.phone.credential.PhoneOtpCredentialProvider;
import cc.coopersoft.keycloak.phone.credential.PhoneOtpCredentialProviderFactory;
import cc.coopersoft.keycloak.phone.providers.constants.TokenCodeType;
import cc.coopersoft.keycloak.phone.providers.exception.PhoneNumberInvalidException;
import cc.coopersoft.keycloak.phone.providers.jpa.TokenCode;
import cc.coopersoft.keycloak.phone.providers.representations.TokenCodeRepresentation;
import cc.coopersoft.keycloak.phone.providers.spi.PhoneVerificationCodeProvider;
Expand All @@ -29,6 +30,7 @@
import java.time.Instant;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class DefaultPhoneVerificationCodeProvider implements PhoneVerificationCodeProvider {

Expand All @@ -54,10 +56,11 @@ private RealmModel getRealm() {
public TokenCodeRepresentation ongoingProcess(String phoneNumber, TokenCodeType tokenCodeType) {

try {
String resultPhoneNumber = Utils.canonicalizePhoneNumber(session, phoneNumber);
TokenCode entity = getEntityManager()
.createNamedQuery("ongoingProcess", TokenCode.class)
.setParameter("realmId", getRealm().getId())
.setParameter("phoneNumber", phoneNumber)
.setParameter("phoneNumber", resultPhoneNumber)
.setParameter("now", new Date(), TemporalType.TIMESTAMP)
.setParameter("type", tokenCodeType.name())
.getSingleResult();
Expand All @@ -75,6 +78,9 @@ public TokenCodeRepresentation ongoingProcess(String phoneNumber, TokenCodeType
return tokenCodeRepresentation;
} catch (NoResultException e) {
return null;
} catch (PhoneNumberInvalidException e) {
logger.warn("Invalid number: "+phoneNumber);
throw new BadRequestException("Phone number is invalid");
}
}

Expand Down Expand Up @@ -199,7 +205,7 @@ public void tokenValidated(UserModel user, String phoneNumber, String tokenCodeI
}
})
.map(CredentialModel::getId)
.toList()
.collect(Collectors.toList())
.forEach(id -> u.credentialManager().removeStoredCredentialById(id));
});
}
Expand Down
17 changes: 17 additions & 0 deletions keycloak-sms-provider-twofactorapi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Twilio SMS Sender Provider

**Not verify in Quarkus 19.0.1**

```sh
cp target/providers/keycloak-phone-provider.jar ${KEYCLOAK_HOME}/providers/
cp target/providers/keycloak-phone-provider.resources.jar ${KEYCLOAK_HOME}/providers/
cp target/providers/keycloak-sms-provider-twilio.jar ${KEYCLOAK_HOME}/providers/


${KEYCLOAK_HOME}/bin/kc.sh build

${KEYCLOAK_HOME}/bin/kc.sh start --spi-phone-default-service=twilio \
--spi-message-sender-service-twilio-account=${account} \
--spi-message-sender-service-twilio-token=${token} \
--spi-message-sender-service-twilio-number=${servicePhoneNumber}
```
81 changes: 81 additions & 0 deletions keycloak-sms-provider-twofactorapi/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>cc.coopersoft</groupId>
<artifactId>keycloak-phone-provider-parent</artifactId>
<version>2.3.4-snapshot</version>
</parent>

<artifactId>keycloak-sms-provider-twofactorapi</artifactId>

<dependencies>
<dependency>
<groupId>cc.coopersoft</groupId>
<artifactId>keycloak-phone-provider</artifactId>
<version>2.3.4-snapshot</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>9.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>${project.build.finalName}</finalName>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
</artifactItem>
</artifactItems>
<outputDirectory>../target/providers</outputDirectory>
<stripClassifier>true</stripClassifier>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package cc.coopersoft.keycloak.phone.providers.sender;

import cc.coopersoft.keycloak.phone.providers.spi.MessageSenderService;
import cc.coopersoft.keycloak.phone.providers.spi.MessageSenderServiceProviderFactory;
import org.keycloak.Config.Scope;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;

public class TwoFactorMessageSenderServiceProviderFactory implements MessageSenderServiceProviderFactory {

private Scope config;

@Override
public MessageSenderService create(KeycloakSession session) {
return new TwoFactorSmsSenderServiceProvider(config,session.getContext().getRealm().getDisplayName());
}

@Override
public void init(Scope config) {
this.config = config;
}

@Override
public void postInit(KeycloakSessionFactory keycloakSessionFactory) {
}

@Override
public void close() {
}

@Override
public String getId() {
return "two-factor";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cc.coopersoft.keycloak.phone.providers.sender;

import cc.coopersoft.keycloak.phone.providers.exception.MessageSendException;
import cc.coopersoft.keycloak.phone.providers.spi.FullSmsSenderAbstractService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jboss.logging.Logger;
import org.keycloak.Config.Scope;

import javax.annotation.PostConstruct;

public class TwoFactorSmsSenderServiceProvider extends FullSmsSenderAbstractService {

private static final Logger logger = Logger.getLogger(TwoFactorSmsSenderServiceProvider.class);
private String twoFactorApiKey;
private static final String twoFactorUrl = "https://2factor.in/API/V1/";
private OkHttpClient client;

@PostConstruct
public void doSetUp() {
client = new OkHttpClient().newBuilder()
.build();
}

TwoFactorSmsSenderServiceProvider(Scope config, String realmDisplay) {
super(realmDisplay);
this.twoFactorApiKey = config.get("twoFactorApiKey");

}

@Override
public void sendMessage(String phoneNumber, String message) throws MessageSendException {

Request request = new Request.Builder()
.url(twoFactorUrl + twoFactorApiKey + "/SMS/" + phoneNumber + "/AUTOGEN/OTP1")
.get()
.build();
try (Response response = client.newCall(request).execute()) {
String responseString = response.body().string();
if (response.isSuccessful()) {
logger.info(responseString + ": sms sent successfully");
} else {
logger.error(responseString + ": sms sending failed");
throw new MessageSendException(response.code(),
String.valueOf(response.code()),
response.message());
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new MessageSendException(400,
String.valueOf(400),
e.getMessage());
}
}

@Override
public void close() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cc.coopersoft.keycloak.phone.providers.sender.TwilioMessageSenderServiceProviderFactory
11 changes: 10 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@
<version.keycloak>21.0.2</version.keycloak>
</properties>


<distributionManagement>
<repository>
<id>github</id>
<name>GitHub OWNER Apache Maven Packages</name>
<url>https://maven.pkg.github.com/cooperlyt/keycloak-phone-provider</url>
</repository>
</distributionManagement>

<modules>
<module>keycloak-phone-provider</module>
<module>keycloak-phone-provider.resources</module>
Expand All @@ -61,7 +70,7 @@
<module>keycloak-sms-provider-yunxin</module>
<module>keycloak-sms-provider-aliyun</module>
<module>keycloak-sms-provider-tencent</module>

<module>keycloak-sms-provider-twofactorapi</module>
</modules>

<dependencies>
Expand Down

0 comments on commit 05a50df

Please sign in to comment.